JavaScript Click处理程序无法在for循环中正常工作 [英] JavaScript click handler not working as expected inside a for loop
问题描述
我正在尝试学习JS并遇到问题.
I'm trying to learn JS and got an issue.
我尝试了很多事情,并且用谷歌搜索,但是都徒劳无功.遵循下面的代码无法按预期工作.我应该在点击时获得i的价值,但它总是返回6.我正在拔头发.请帮助.
I tried many things and googled but all in vain. Following piece of code doesn't work as expected. I should get value of i on click but it always returns 6. I'm pulling my hair out., please help.
for (var i = 1; i < 6; i++) {
console.log(i);
$("#div" + i).click(
function() {
alert(i);
}
);
}
推荐答案
这是经典的JavaScript关闭问题.对i
对象的引用存储在单击处理程序闭包中,而不是i
的实际值.
This is a classic JavaScript closure problem. Reference to the i
object is being stored in the click handler closure, rather than the actual value of i
.
每个单击处理程序都将引用同一个对象,因为只有一个计数器对象包含6个,因此每次点击可获得6个.
Every single click handler will refer to the same object because there’s only one counter object which holds 6 so you get six on each click.
解决方法是将其包装在一个匿名函数中,然后将i作为参数传递.在函数调用中按值复制基元.
The workaround is to wrap this in an anonymous function and pass i as argument. Primitives are copied by value in function calls.
for(var i=1; i<6; i++) {
(function (i) {
$("#div" + i).click(
function () { alert(i); }
);
})(i);
}
更新
或者您可以使用让" 代替var
来声明i
. let
每次都为您提供新的绑定.它只能在ECMAScript 6 strict mode
中使用.
Or you can use 'let' instead var
to declare i
. let
gives you fresh binding each time. It can only be used in ECMAScript 6 strict mode
.
'use strict';
for(let i=1; i<6; i++) {
$("#div" + i).click(
function () { alert(i); }
);
}
这篇关于JavaScript Click处理程序无法在for循环中正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!