简体   繁体   English

for循环中的JavaScript闭包

[英]JavaScript closures in for-loop

As explained here http://www.mennovanslooten.nl/blog/post/62/ code below outputs result just for "5x5" forgetting about anything before that. 正如这里所解释的http://www.mennovanslooten.nl/blog/post/62/以下代码输出的结果仅为“5x5”之前忘记了任何事情。

for (x = 1; x <= 5; x++) {
for (y = 1; y <= 5; y++) {

    var cords = x+"x"+y;
    var el = document.getElementById(cords);
    el.addEventListener("click", function (e) { B_modeWindow('1', cords); });

}
}

As far I have the informations (blog link provided above) can't figure out how to alter showed code to fix it. 到目前为止,我有信息(上面提供的博客链接)无法弄清楚如何更改显示代码来修复它。

How to walk around this code with JavaScript closure in my for-loop? 如何在我的for循环中使用JavaScript闭包来遍历此代码?

edit: I dont get it. 编辑:我不明白。 varibles are defined in good way. varibles以良好的方式定义。 Test: 测试:

for (x = 1; x <= 5; x++) {
for (y = 1; y <= 5; y++) {

    var cords = x+"x"+y;
    alert(cords);

}
}

Call the function with anything you need to be closed as an argument. 使用您需要作为参数关闭的任何内容调用该函数。 In this case, that's cords . 在这种情况下,那是cords

for (x = 1; x <= 5; x++) {
    for (y = 1; y <= 5; y++) {
        var cords = x + "x" + y;
        var el = document.getElementById(cords);

        (function(cords) {
            el.addEventListener("click", function (e) { B_modeWindow('1', cords); });
        })(cords);
    }
}

Minitech was close, but you have to move the closed variables INSIDE the function: Minitech很接近,但你必须在函数内移动闭合变量:

for (x = 1; x <= 5; x++) {
    for (y = 1; y <= 5; y++) {
        (function() {
            var cords = x + "x" + y;
            var el = document.getElementById(cords);
            el.addEventListener("click", function (e) { B_modeWindow('1', cords); });
        })();
    }
}

The problem is that js variables have function scope, so the cords variable gets rewritten as you go through the loop. 问题是js变量有函数作用域,因此当你通过循环时,cords变量会被重写。 Thus all listener functions point to the same variable which ends up with the final value. 因此,所有侦听器函数都指向同一个变量,该变量以最终值结束。 One solution to this is to create another function that takes el and cords as arguments and adds a cords-based listener to el. 对此的一个解决方案是创建另一个将el和cords作为参数的函数,并向el添加基于cords的侦听器。 Then call this function from your inner loop rather than adding the listener there directly. 然后从内循环调用此函数,而不是直接在其中添加侦听器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM