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 ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…