javascript中计数器变量的奇怪值 [英] Weird value for counter variable in javascript
本文介绍了javascript中计数器变量的奇怪值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
Javascript臭名昭着的循环问题?
出于某种原因,我得到6 在我的函数里面为每个div元素:
For some reason I get "6" inside my function here for every div element:
for(var i = 1; i <= 5; i++){
$('<div class="e-' + i + '"></div>').appendTo(something).click(function(){
alert(i); // <-- it's 6. wtf??
});
}
而不是1,2,3等
另一方面,该课程似乎设置正确..
The class on the other hand it appears to be correctly set..
我做错了什么?
推荐答案
您的 for
循环正在页面加载时执行。警报仅在for循环结束后发生单击事件时触发。因此, i
的值现在为6。
Your for
loop is being executed at page load time. The alert only fires when there's a click event which is happening after the for loop has finished. Hence the value of i
is now 6.
1)页面加载,为
循环做它的东西......
1) Page loads, for
loop does its stuff...
2)稍后会触发一个click事件。此时 i
的值为6,因为循环的已经完成。
2) Sometime later a click event is fired. the value of i
at this time is 6 because the for
loop has already completed.
这篇关于javascript中计数器变量的奇怪值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文