for 循环中的闭包
循环中的闭包给我带来了问题。我想我必须创建另一个返回函数的函数来解决问题,但我无法让它与我的 jQuery 代码一起工作。
这是简化形式的基本问题:
function foo(val) {
alert(val);
}
for (var i = 0; i < 3; i++) {
$('#button'+i).click(function(){
foo(i);
});
}
自然地,单击三个按钮中的任何一个都会发出警报,提示“3”。我想要的功能是,单击按钮 1 将发出警报,提示“1”,按钮 2 将发出警报,提示“2”等。
如何我可以让它这样做吗?
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);
});
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请参阅 bind 方法。
来自文档:
See the bind method.
From the docs:
试试这段代码:
这里有一些要点:
i
的每个值都被复制到新的作用域中作为k
,并且从funMaker
返回的函数在k 附近关闭
(在循环中不会改变),而不是在i
周围(在循环中会改变)。click
的函数不“拥有”i
,它会关闭i
它的创建者,并且i
在循环中发生变化。funMaker
编写,但我通常使用此类辅助函数来使事情更清晰。funMaker
的参数是k
,但这没有什么区别,它可以是i
没有任何问题,因为它存在于函数funMaker
。编辑:修正了一些标点符号。
Try this code:
Some important points here:
i
is copied in a new scope ask
, and the function returned fromfunMaker
closes aroundk
(which doesn't change in the loop), not aroundi
(which does).click
doesn't 'own' thei
, it closes over thei
of its creator, and thati
changes in the loop.funMaker
inlined, but I usually use such helper functions to make things clearer.funMaker
isk
, but that makes no difference, it could have beeni
without any problems, since it exists in the scope of the functionfunMaker
.EDIT: Fixed some punctuation.
@Andy 解决方案是最好的。但您也可以使用 Javascript 作用域来帮助您保存闭包中的值。
您可以通过执行匿名函数在循环体中创建新作用域来实现此目的。
由于循环体在每次迭代时都是一个新范围,因此索引变量在每次迭代时都会使用正确的值进行复制。
@Andy solution is the nicest. But you can also use Javascript scoping to help you save the value in your closure.
You do so by creating a new scope in your loop body by executing an anonymous function.
Since the loop body is a new scope at each iteration, the index variable is duplicated with the correct value at each iteration.
使用 jquery 中的 .each 函数 - 我猜你循环遍历类似的元素 - 所以使用类似的内容添加点击:
未测试,但我总是在可能的情况下使用这种结构。
Use the .each function from jquery - I guess you a looping through similar elements - so add the click using something like:
Not tested but I always use this kind structure where possible.
或者只是制造一个新功能,正如您所描述的。它看起来像这样:
我很确定迈赫达德的解决方案不起作用。当您看到人们复制到临时变量时,通常是为了保存“this”的值,该值在内部子作用域内可能不同。
Or just manufacture a new function, as you describe. It would look like this:
I'm pretty sure Mehrdad's solution doesn't work. When you see people copying to a temporary variable, it's usually to save the value of "this" which may be different within an inner child scope.