shr*_*ans 6 javascript arrays variables jquery
我有一些按钮,存储在一个数组中.然后我循环遍历该数组,为每个按钮添加一个click事件.每次单击都会提醒值i.我希望值是1,2,3等等,但他们总是回来作为一个值,在情况3.
你能解释为什么会发生这种情况以及如何解决它吗?
请看这个jsFiddle.代码如下:
var theButtons = ['.button.one', '.button.two', '.button.three'];
for (i=0; i<theButtons.length; i++) {
$(theButtons[i]).click(function () {
alert(i); // always returns 3
});
}
Run Code Online (Sandbox Code Playgroud)
请尽可能简单明了地解释它 - 我有点像Javascript和编程的初学者.
Nea*_*eal 11
当你点击按钮时i === 3.需要将值传递i给闭包:
for (var i = 0; i<theButtons.length; i++) { // do `var i` so the i is not global
(function(index){
$(theButtons[i]).on('click', function () {
alert(index); // index === the value that was passed
});
})(i); // pass the value of i
}
Run Code Online (Sandbox Code Playgroud)
小提琴演示:http://jsfiddle.net/maniator/fE55Y/3/