在包含循环变量的循环中定义匿名函数? [英] Defining anonymous functions in a loop including the looping variable?

查看:103
本文介绍了在包含循环变量的循环中定义匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这段代码不起作用,我也知道为什么。
然而,我不知道如何解决它:



JavaScript:

  var $ = function(id){return document.getElementById(id); }; 
document.addEventListener('DOMContentLoaded',function()
{
for(var i = 1; i <= 3; i ++)
{
$( 'a'+ i).addEventListener('click',function()
{
console.log(i);
});
}
}) ;

HTML:

 < a href =#id =a1> 1< / a> 
< a href =#id =a2> 2< / a>
< a href =#id =a3> 3< / a>

我希望它打印您点击的链接的编号,而不是4。
我宁愿避免使用节点的属性(id或content),而是修正循环。

解决方案

将循环块封装在它自己的匿名函数中:

$ p $ document $ add $ b {
for(var i = 1; i <= 3; i ++)
{
(function(i){
$('a'+ i).addEventListener ('click',function(){
console.log(i);
})
})(i);
}
}

这会创建一个新的 i 函数在每个调用/迭代中都没有,在没有这个本地副本的情况下,传递给 addEventListener (每次迭代)的每个函数都会关闭对相同变量 ,这些回调执行的时候,它的值等于 4


I know that this code doesn't work and I also know why. However, I do not know how to fix it:

JavaScript:

var $ = function(id) { return document.getElementById(id); };
document.addEventListener('DOMContentLoaded', function()
{
    for(var i = 1; i <= 3; i++)
    {
        $('a' + i).addEventListener('click', function()
        {
            console.log(i);
        });
    }
});

HTML:

<a href="#" id="a1">1</a>
<a href="#" id="a2">2</a>
<a href="#" id="a3">3</a>

I want it to print the number of the link you clicked, not just "4". I will prefer to avoid using the attributes of the node (id or content), but rather fix the loop.

解决方案

Wrap the loop block in its own anonymous function:

document.addEventListener('DOMContentLoaded', function()
{
        for(var i = 1; i <= 3; i++)
        {
            (function(i) {
                $('a' + i).addEventListener('click', function() {
                    console.log(i);
                })
            })(i);
        }
}

This creates a new instance of i that's local to the inner function on each invocation/iteration. Without this local copy, each function passed to addEventListener (on each iteration) closes over a reference to the same variable, whose value is equal to 4 by the time any of those callbacks execute.

这篇关于在包含循环变量的循环中定义匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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