for循环中的闭包 [英] Closures in a for loop

查看:25
本文介绍了for循环中的闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

循环中的闭包给我带来了问题.我想我必须制作另一个返回函数的函数来解决问题,但我无法让它与我的 jQuery 代码一起工作.

Closures in a loop are causing me problems. I think I have to make another function that returns a function to solve the problem, but I can't get it to work with my jQuery code.

这是一个简化形式的基本问题:

Here is the basic problem in a simplified form:

function foo(val) {
  alert(val);
}

for (var i = 0; i < 3; i++) {
  $('#button'+i).click(function(){
    foo(i);
  });
}

自然地点击三个按钮中的任何一个都会给出提示 3.我想要的功能是点击按钮 1 会给出提示 1,按钮 2 会提示 2 等等.

Naturally clicking on any of the three buttons will give an alert saying 3. The functionality I want is that clicking on button 1 will give an alert saying 1, button 2 will say 2 etc.

我怎样才能做到这一点?

How can I make it do that?

推荐答案

参见 bind 方法.

$('#button'+i).bind('click', {button: i}, function(event) {
  foo(event.data.button);
});

来自文档:

可选的 eventData 参数是不常用.提供时,这参数允许我们传递额外的信息给处理程序.一个得心应手使用这个参数是为了工作围绕关闭引起的问题

The optional eventData parameter is not commonly used. When provided, this argument allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures

这篇关于for循环中的闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆