Reputation: 4516
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);
}
}
Upvotes: 0
Views: 161
Reputation: 780645
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); });
})();
}
}
Upvotes: 1
Reputation: 21756
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.
Upvotes: 0
Reputation: 224862
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);
}
}
Upvotes: 1