简体   繁体   中英

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.

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?

edit: I dont get it. varibles are defined in good way. 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 .

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:

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. 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. Then call this function from your inner loop rather than adding the listener there directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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