JavaScript和传递事件实例来运行

时间:2012-07-30 13:38:38

标签: javascript javascript-events

尝试从onclick事件传递事件对象时,我遇到了跨浏览器问题。

目前,我正在做以下

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并不尊重window.event。但是,我还能通过它吗?

我诉诸于&#34;而不是&#34;清洁解决方案:

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);
  }
}

有人可以推荐更好的解决方法吗?我真的不喜欢我做的解决方法。

谢谢,

2 个答案:

答案 0 :(得分:0)

var handler = function (evt) {
    // do something here
}

if(window.addEventListener) {
    link.addEventListener("click", handler);
} else if(document.attachEvent) {
    link.attachEvent("onclick", handler)
}

答案 1 :(得分:0)

如果我理解正确,您希望您的处理程序在调用时可以访问el变量和事件对象。这是可能的而不是那么难,但你可能想要了解闭包:

link.onclick = (function(el)
{
    return function (e)//this function will receive the event object
    {
        e = e || window.event;//for ie
        LinkManager.HandleOnClick(e, el);
    }
})(link);

但是,老实说,这太过分了,试试这个(双关语):

link.onclick = function(e)
{//this refers to `link`, the clicked element
    e = e || window.event;//for ie
    LinkManager.HandleOnClick(e, this);
};

甚至更少的代码:

link.onclick = function(e)
{//this refers to `link`, the clicked element
    e = e || window.event;//for ie
    LinkManager.HandleOnClick.apply(this,[e]);
    //LinkManager.HandleOnClick will receive 1 argument, the event object, and 'this' will point to 'link'
};

甚至更少:

link.onclick = LinkManager.HandleOnClick;//this === link, 1 argument: the event object

也就是说,您正在迭代列表,并将事件侦听器附加到每个子元素。我强烈建议你使用delegaion:

if (list.addEventListener)
{
    list.addEventListener('click',LinkManager.HandleOnClick,false);
}
else if (list.attachEvent)
{
    list.attachEvent('onclick',LinkManager.HandleOnClick);
}
else
{
    //use the loop you have now as a last resort
}

//LinkManager.HandleOnClick should start like so:
LinkManager.HandleOnClick = function(e)
{
    e = e || window.event;//<- you have the event object here
    var target = e.target || e.srcElement;//=== list item: your link variables, your element
    console.log(this);//<-should reference the list element (<ul> || <ol>)
};

无论如何,这就是我要解决的问题