如果我理解正确,您希望您的处理程序在调用时能够访问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
也就是说,您正在迭代一个列表,并将一个事件侦听器附加到每个单独的子元素。我强烈建议您使用 delegion:
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>)
};
不管怎样,我就是这样解决这个问题的