Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  116] [ 5]  / answers: 1 / hits: 8745  / 9 Years ago, wed, may 27, 2015, 12:00:00

Im creating input elements in a loop.
On click, these buttons are supposed to call a certain function with a certain Parameter, based on the Initial creation of the button element.
What in fact does happen is that all Buttons always call the function with Parameter from the LAST button.



for (var i = 0; i < planets.length; i++){
var id = planets[i].id;

var input = document.createElement(input);
input.type = button;
input.className = worldButton;
input.value = Choose this world;
Input.onclick = function(){
game.pickWorld(planets, id);
}
}


Each button always seems to pass on the id of planets[planets.length] instead of planets[i].
console.log(id) is correct.
It doesnt matter if use onclick, addEventListener or jquery.click.



The whole planets Array however is passed on successfully.



How can i get the Input to correctly pass on the id of that particular Iteration ?


More From » loops

 Answers
3

You need to use an IIFE and create a new closure like


for (var i = 0; i < planets.length; i++){
var id = planets[i].id;

var input = document.createElement("input");
input.type = "button";
input.className = "worldButton";
input.value = "Choose this world";

input.onclick = (function(id, planets){
return function(){
game.pickWorld(planets, id);
}
})(id,planets);
}

What was happening is the variables planets and id were visible to the callback function and at execution time, were using the last iterated value.


However, with a closure, you effectively created a 'private' variable seen and preserved by each callback function.


[#36843] Tuesday, May 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breap

Total Points: 606
Total Questions: 96
Total Answers: 108

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
;