JavaScript for loop index strangeness(JavaScript for 循环索引异常)
问题描述
我对 JS 比较陌生,所以这可能是一个常见问题,但在处理 for 循环和 onclick 函数时我注意到了一些奇怪的问题.我能够用这段代码复制问题:
I'm relatively new to JS so this may be a common problem, but I noticed something strange when dealing with for loops and the onclick function. I was able to replicate the problem with this code:
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var buttons = document.getElementsByTagName('a');
for (var i=0; i<2; i++) {
buttons[i].onclick = function () {
alert(i);
return false;
}
}
}
</script>
</head>
<body>
<a href="">hi</a>
<br />
<a href="">bye</a>
</body>
</html>
点击链接时,我希望得到0"和1",但我却得到了2".这是为什么呢?
When clicking the links I would expect to get '0' and '1', but instead I get '2' for both of them. Why is this?
顺便说一句,我设法通过使用this"关键字解决了我的特定问题,但我仍然很好奇这种行为背后的原因.
BTW, I managed to solve my particular problem by using the 'this' keyword, but I'm still curious as to what is behind this behavior.
推荐答案
你有 for
循环中非常常见的闭包问题.
You are having a very common closure problem in the for
loop.
封闭在一个闭包中的变量共享同一个环境,所以当 onclick
回调被执行时,循环已经运行并且 i
变量将是left 指向最后一个条目.
Variables enclosed in a closure share the same single environment, so by the time the onclick
callback is executed, the loop has run its course and the i
variable will be left pointing to the last entry.
你可以用更多的闭包来解决这个问题,使用函数工厂:
You can solve this with even more closures, using a function factory:
function makeOnClickCallback(i) {
return function() {
alert(i);
return false;
};
}
var i;
for (i = 0; i < 2; i++) {
buttons[i].onclick = makeOnClickCallback(i);
}
如果您不熟悉闭包的工作原理,这可能是一个相当棘手的话题.您可以查看以下 Mozilla 文章进行简要介绍:
This can be quite a tricky topic, if you are not familiar with how closures work. You may to check out the following Mozilla article for a brief introduction:
- 使用闭包
注意:我还建议不要在 for
循环中使用 var
,因为这可能会欺骗您相信 i
变量具有块作用域,而另一方面,i
变量就像 buttons
变量一样,作用于函数内.
Note: I would also suggest not to use var
inside the for
loop, because this may trick you in believing that the i
variable has block scope, when on the other hand the i
variable is just like the buttons
variable, scoped within the function.
这篇关于JavaScript for 循环索引异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript for 循环索引异常


- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01