在 for 循环中分配点击处理程序 [英] Assign click handlers in for loop
问题描述
我有几个 div 的 #mydiv1
、#mydiv2
、#mydiv3
,...并且想为它们分配点击处理程序:
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);
});
}
});
但是当点击 #mydiv3
时没有显示 'you clicked 3'
(对于其他每次点击),我得到 'you clicked 20'代码>.我做错了什么?
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?
推荐答案
创建 循环中的闭包.你需要有这样的回调函数:
It's a common mistake to create closures in loops in Javascript. You need to have some sort of callback function like this:
function createCallback( i ){
return function(){
alert('you clicked' + i);
}
}
$(document).ready(function(){
for(var i = 0; i < 20; i++) {
$('#question' + i).click( createCallback( i ) );
}
});
<小时>
2016 年 6 月 3 日更新: 由于这个问题仍然受到一些关注,而且 ES6 也越来越流行,我建议采用现代解决方案.如果你写 ES6,你可以使用 let
关键字,这使得 i
变量对于循环来说是局部的,而不是全局的:
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 the i
variable local to the loop instead of global:
for(let i = 0; i < 20; i++) {
$('#question' + i).click( function(){
alert('you clicked ' + i);
});
}
它更短也更容易理解.
这篇关于在 for 循环中分配点击处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!