Working DEMO
(工作演示)
This is a classic JavaScript closure problem.
(这是一个典型的JavaScript闭包问题。)
Reference to the i
object is being stored in the click handler closure, rather than the actual value of i
.(对i
对象的引用存储在单击处理程序闭包中,而不是i
的实际值。)
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.
(每个单击处理程序都将引用同一个对象,因为只有一个计数器对象可以容纳6,因此每次单击时会得到6个。)
The workaround is to wrap this in an anonymous function and pass i as argument.
(解决方法是将其包装在匿名函数中并将i作为参数传递。)
Primitives are copied by value in function calls.(在函数调用中按值复制基元。)
for(var i=1; i<6; i++) {
(function (i) {
$("#div" + i).click(
function () { alert(i); }
);
})(i);
}
UPDATE
(UPDATE)
Updated DEMO
(更新了DEMO)
Or you can use 'let' instead var
to declare i
.
(或者您可以使用'let'代替var
来声明i
。)
let
gives you fresh binding each time.(let
每次都给你新鲜的装订。)
It can only be used in ECMAScript 6 strict mode
.(它只能在ECMAScript 6 strict mode
。)
'use strict';
for(let i=1; i<6; i++) {
$("#div" + i).click(
function () { alert(i); }
);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…