When creating a set of buttons I came across a strange behaviour. When writing it first, I expected every button to display its own number when clicked, but apparently this is not the case. But strangely I still get two different behaviours depending on how I define the string that should be displayed. So my questions are:
- Why do the two examples produce different outcomes, ans why are they different from what is displayed when we assign something using
innerHTML
? - What do I have to change for getting the outcome I originally wanted? (Each button click displays own number.)
function test(){
var foo = document.getElementById("foo")
var bar = document.getElementById("bar")
for(var k=0; k < 2; k++){
// 1st example
var a = document.createElement("button")
a.innerHTML = "A button "+k
var str = "click " + k
a.onclick = function(){alert(str)}
foo.appendChild(a)
// 2nd example
var b = document.createElement("button")
b.innerHTML = "B button "+k
b.onclick = function(){alert("click " + k)}
bar.appendChild(b)
}
}
test()
<div id="foo">
</div>
<div id="bar">
</div>