我正在尝试将函数绑定(bind)到 Internet Explorer 7 中节点列表中的项目。
for(var j = 0; j < navLabels.length; j++)
{
navInsets[j].onmouseover = function(){showLabel(navLabels[j], true);};
navInsets[j].onmouseout = function(){showLabel(navLabels[j], false);};
navInsets[j].onclick = function(){selectNew(j);};
navLabels[j].onclick = function(){selectNew(j);};
}
showLabel() 和 selectNew() 都是我自己的函数。它们每个都需要传递一个索引,在本例中为 j。
我知道,在匿名函数内部,j 最终将成为对 j 的引用,而不是 j 的值。我也知道我可以使用 addEventListener 或 bind 方法来执行此操作,但这两种方法在 IE 7 中都是不允许的。我什至知道 AttachEvent 方法适用于 ie7,但由于我需要传递参数,所以我需要换行匿名函数中的函数使用attachEvent(至少看起来是这样),这就是最初的问题。
关于这个主题有什么不太老套的想法吗?谢谢。
最佳答案
使用匿名函数来隐藏j
:
(function(j) {
navInsets[j].onclick = function() {selectNew(j);};
...
})(j);
这将强制 j
在函数范围内按值传递。
关于javascript - 在循环中附加事件 (IE 7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14593899/