Why is the alert I get always "You clicked button 5" in this example? How can I get n to stay at the right value inside the event handler?
html:
<div id="container"></div>
js:
var container = document.getElementById("container");
for ( var n = 0; n < 5; n++) {
var btn = document.createElement("button");
btn.innerHTML = "Button " + n;
btn.onclick = function() {
alert("You clicked button " + n);
}
container.appendChild(btn);
}
I realize in this example I could just use something like this.innerHTML or assign an attribute to the button with n as its value, but i'm not interested in doing it that way.
heres the fiddle: http://jsfiddle.net/WFNL2/1/