将索引值绑定到事件处理程序
这里我的目的是迭代一个元素数组,并在每个元素上设置一个事件处理程序,同时还将当前迭代器值绑定到该事件处理程序。我想出的是:
for (var i = 0; i < elementArray.length; ++i)
{
var elem = elementArray[i];
elem.onmouseover = function() { foo(i); }
}
function foo(index)
{
alert(index);
}
这里我使用闭包将 i
绑定到 foo
。问题在于,当实际调用 foo
时,i
始终等于 elementArray.length
,因为当然,当 foo<调用 /code> 时,
i
已递增到最大值。我认为,我想要的是将 i
的新副本绑定到每个匿名函数,以便它将正确的值传递给 foo
。但我不确定最好的方法是什么。
Here my intent is to iterate over an array of elements, and set an event handler on each element while also binding the current iterator value to that event handler. What I've come up with is:
for (var i = 0; i < elementArray.length; ++i)
{
var elem = elementArray[i];
elem.onmouseover = function() { foo(i); }
}
function foo(index)
{
alert(index);
}
Here I use a closure to bind i
to foo
. The problem is that when foo
is actually invoked, i
is always equal to elementArray.length
, because of course, when foo
is invoked i
has already been incremented to the maximum value. What I want here, I think, is for a new copy of i
to be bound to each anonymous function, so that it passes the correct value to foo
. But I'm not sure what the best way to do this is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这对您不起作用,因为当调用
mouseover
处理程序时,i
的值已更改,它等于elementArray.length.相反,您应该做的是返回一个函数,该函数创建一个闭包并在定义时保存 i 的值。
This isn't working for you because by the time the
mouseover
handler is invoked, the value ofi
has changed, it is equal toelementArray.length
. What you should do instead is return a function which creates a closure and holds the value ofi
at the time it is defined.您可以使用 Function.prototype.bind (或为不支持它的浏览器)以避免(显式)关闭。那么你的调用将被写为:
You can use Function.prototype.bind (or define one for the browsers that do not support it) to avoid (explicit) closures. Then your calls would be written as: