JavaScript for 循环索引异常 [英] JavaScript for loop index strangeness

查看:15
本文介绍了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 循环索引异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆