I have logic in which I need to dynamically build HTML elements where the parameters of the function given to an event element are dependent on the iteration variable.
The example below does not include parameters but it does produce the same behavior I wish to correct.
Here, the value of i will be shadowed by each iteration resulting in a value of '10' being alerted for each button that is clicked.
I'd like to not only correct this behavior (so that each button alerts the value corresponding to the iteration in which it was created) without drastically changing my approach but also gain a better understanding of why this behavior is occurring.
for (var i = 1; i<10; i++) {
var newButton = document.createElement("button");
newButton.innerHTML = "Button" + i;
newButton.onclick = function() { alert(i) };
document.getElementById('container').appendChild(newButton);
}
jsfiddle: https://jsfiddle.net/poggtfnx/3/