I am facing a cross browser issue while trying to pass an event object from an onclick event.
Currently, I am doing the following
for (var i = 0; i < list.length; i++)
{
var link= list[i];
link.onclick = function(el) { return function () {LinkManager.HandleOnClick(window.event, el); }}(link);
}
Firefox doesn’t respect window.event. However, how else can I pass it?
I resorted to a "not" clean solution:
for (var i = 0; i < list.length; i++)
{
var link= list[i];
link.onclick = SomeClickHandler;
}
function SomeClickHandler(e)
{
e = e || window.event;
if (typeof (e) !== 'undefined')
{
var element = e.target || e.srcElement;
LinkManager.HandleOnClick(e, element);
}
}
Can anyone recommend a better way of solving it? I really didn’t like the workaround that I did.
If I understand correctly, you want your handler to have access to the
elvariable and the event object when it’s called. That’s possible and not that hard, but you might want to read up on closures:but, to be honest, this is overkill, try this (pun intended):
or even less code:
and even less:
That said, you’re iterating a list, and attaching an event listener to each individual child element. I’d strongly advise you to use delegaion:
Anyway, that’s how I’d tackle this