This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var animals = ["aligator", "bat", "cow"]; | |
var bad = document.getElementById("bad"); | |
for (var i = 0; i < animals.length; i++) { | |
var animal = animals[i]; | |
var input = document.createElement("input"); | |
input.type = "button"; | |
input.value = animal; | |
input.style.marginLeft = "5px"; | |
input.onclick = function() {alert(animal);}; | |
bad.appendChild(input); | |
} |
The problem is that the animal variable used in the button's onclick event is changed in the loop and thus the event will use the value that was last assigned to the variable. In order to get the onclick event to use the value of the variable at the time the onclick is defined you will need to define an execution context which will capture this value. This can be done using a function. While this can be done with a regular function here is a nifty little example of doing this with an anonymous function:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var animals = ["aligator", "bat", "cow"]; | |
var good = document.getElementById("good"); | |
for (var i = 0; i < animals.length; i++) { | |
var animal = animals[i]; | |
var input = document.createElement("input"); | |
input.type = "button"; | |
input.value = animal; | |
input.style.marginLeft = "5px"; | |
input.onclick = (function(animal) {return function() {alert(animal);};})(animal); | |
good.appendChild(input); | |
} |
Here is a slightly different (possibly simpler) way to create the function closure:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var animals = ["aligator", "bat", "cow"]; | |
var better = document.getElementById("better"); | |
for (var i = 0; i < animals.length; i++) { | |
var input = document.createElement("input"); | |
input.type = "button"; | |
input.value = animals[i]; | |
input.style.marginLeft = "5px"; | |
(function() { | |
var animal = animals[i]; | |
input.onclick = function() {alert(animal);}; | |
})(); | |
better.appendChild(input); | |
} |