在 for 循环中分配点击处理程序
我有几个 div 的 #mydiv1
、#mydiv2
、#mydiv3
...,并且想要为它们分配点击处理程序:
$(document).ready(function(){
for(var i = 0; i < 20; i++) {
$('#question' + i).click( function(){
alert('you clicked ' + i);
});
}
});
但是相反当点击 #mydiv3
时显示'you clicked 3'
(与其他每次点击一样),我得到'you clicked 20'
。我做错了什么?
I'm having several div's #mydiv1
, #mydiv2
, #mydiv3
, ... and want to assign click handlers to them:
$(document).ready(function(){
for(var i = 0; i < 20; i++) {
$('#question' + i).click( function(){
alert('you clicked ' + i);
});
}
});
But instead of showing 'you clicked 3'
when click on #mydiv3
(as for every other click) I get 'you clicked 20'
. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在循环中创建闭包 在 JavaScript 中。您需要有某种回调函数,如下所示:
2016 年 6 月 3 日更新: 因为这个问题仍然受到一些关注,而且 ES6 也越来越流行,所以我建议一个现代的解决方案。如果您编写 ES6,则可以使用
let
关键字,这使得i
变量成为循环的本地变量而不是全局变量:它更短且更易于理解。
It's a common mistake to create closures in loops in Javascript. You need to have some sort of callback function like this:
Update June 3, 2016: since this question is still getting some traction and ES6 is getting popular as well, I would suggest a modern solution. If you write ES6, you can use the
let
keyword, which makes thei
variable local to the loop instead of global:It's shorter and easier to understand.
澄清一下,i 等于 20,因为只有在循环完成后才会触发单击事件。
To clarify, i is equal to 20 because the click event won't have fired until after the loop has finished.
使用 on 附加“点击”处理程序,您可以使用事件数据来传递数据,例如在:
Using on to attach the 'click' handler you can use the event data in order to pass your data like in:
您可以通过分配一次单击处理程序来完成(或者至少不会进行许多不必要的关闭)。将所有 div 放入一个类
mydivs
中,然后:使用
slice
字符串方法去除首字母。它可能会更好
注意:使用
You can get by with assigning the click handler once (or at least not making many unnecessary closures). Put all the divs in one class
mydivs
, then:This looks at the element's ID to get its number, using the
slice
string method to strip the initial letters off.Note: It may be better to use
instead of
一般来说,如果您希望将点击句柄分配给大量项目,则需要一个容器(更高级别的 div)来为您解释点击,因为点击从 dom 中冒出。
Generally, if you are looking to assign click handles to a large number of items, you want to have a container (higher level div) that interprets the clicks for you, as the click bubbles up from the dom.