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 循环索引异常
基础教程推荐
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
