本文介绍了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 forloop has already completed.
更多推荐
javascript中计数器变量的奇怪值
发布评论