javascript中计数器变量的奇怪值

编程入门 行业动态 更新时间:2024-10-22 10:34:50
本文介绍了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中计数器变量的奇怪值

本文发布于:2023-11-22 06:47:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616380.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   计数器   奇怪   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!