JavaScript for循环索引奇怪 [英] JavaScript for loop index strangeness

查看:110
本文介绍了JavaScript for循环索引奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JS比较陌生,所以这可能是一个常见的问题,但是我在处理for循环和onclick函数时发现了一些奇怪的东西。我能够用这个代码复制这个问题:

$ $ p $ < html>
< head>

< script type =text / javascript>
window.onload = function(){
var buttons = document.getElementsByTagName('a'); (i);
for(var i = 0; i <2; i ++){
buttons [i] .onclick = function(){
alert(i)
返回false;
}
}
}

< / script>

< / head>

< body>
< a href => hi< / a>
< br />
< a href => bye< / a>

< / body>

< / html>

点击链接时,我希望得到'0'和'1',但是我得到'2'为他们两个。为什么会这样?



顺便说一句,我设法通过使用'this'来解决我的特殊问题,但是我仍然对这个行为背后的问题感到好奇。

解决方案

您有 循环中的一个非常常见的关闭问题。



闭包中的变量共享同一个单独的环境,所以到执行 onclick 回调时,循环已经运行, 变量将被指向最后一项。



你可以用函数工厂来解决这个问题。函数makeOnClickCallback(i){
返回函数(){
alert(i);

  
返回false;
};
}

var i; (i = 0; i <2; i ++){
buttons [i] .onclick = makeOnClickCallback(i);







$ b这可能是一个相当棘手的话题,如果你不熟悉如何关闭工作。您可以查看下面的Mozilla文章进行简要介绍:






注意:我也建议不要在循环内使用 var ,因为这可能欺骗你相信 i 变量具有块范围,另一方面, i 变量就像按钮变量,在函数范围内。


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>

When clicking the links I would expect to get '0' and '1', but instead I get '2' for both of them. Why is 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.

解决方案

You are having a very common closure problem in the for loop.

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);
}

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:


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天全站免登陆