<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
document.getElementById('btn-' + btnNum).onclick = function() {
alert(prizes[btnNum]);
}
}
The reason why this doesn't work is because when a function accesses a variable outside its scope, it accesses that variable, not a frozen copy, so when a user clicks a button, they will always get undefined since the for loop has already incremented btnNum to 3. prizes[3] is undefined.
My question is, does the same hold true for the document.getElementById('btn-' + btnNum)? Is the for loop attaching 3 event handlers to btn3? Or is it still attaching a click handler to each button, even though they will all alert undefined.
I'm asking a different question, not just trying to get the code to work.