将索引值绑定到事件处理程序

发布于 2025-01-08 07:00:42 字数 560 浏览 0 评论 0原文

这里我的目的是迭代一个元素数组,并在每个元素上设置一个事件处理程序,同时还将当前迭代器值绑定到该事件处理程序。我想出的是:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初熏 2025-01-15 07:00:42

这对您不起作用,因为当调用 mouseover 处理程序时,i 的值已更改,它等于 elementArray.length.相反,您应该做的是返回一个函数,该函数创建一个闭包并在定义时保存 i 的值。

for (var i = 0; i < elementArray.length; ++i)
{
      var elem = elementArray[i];
      elem.onmouseover = foo(i);
}

function foo(index)
{
    return function(){
       alert(index);
    }
}

This isn't working for you because by the time the mouseover handler is invoked, the value of i has changed, it is equal to elementArray.length. What you should do instead is return a function which creates a closure and holds the value of i at the time it is defined.

for (var i = 0; i < elementArray.length; ++i)
{
      var elem = elementArray[i];
      elem.onmouseover = foo(i);
}

function foo(index)
{
    return function(){
       alert(index);
    }
}
暮年慕年 2025-01-15 07:00:42

您可以使用 Function.prototype.bind (或为不支持它的浏览器)以避免(显式)关闭。那么你的调用将被写为:

elem.onmouseover = function(x) { foo(x); }.bind(this, i); 

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:

elem.onmouseover = function(x) { foo(x); }.bind(this, i); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文