Skip to content

Instantly share code, notes, and snippets.

@marekdano
Created January 28, 2019 22:25
Show Gist options
  • Save marekdano/23c31e1666943c50963ca7565fbad9fd to your computer and use it in GitHub Desktop.
Save marekdano/23c31e1666943c50963ca7565fbad9fd to your computer and use it in GitHub Desktop.
<!-- The issue: alert displays 'undefined' instead of an item from prizes -->
<button id="btn-0">Button 1</button>
<button id="btn-1">Button 2</button>
<button id="btn-2">Button 3</button>
<script type="text/javascript">
const prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
// For each of our buttons, when the user clicks it...
document.getElementById(`btn-${btnNum}`).onclick = () => {
// Tell her what she's won!
alert(prizes[btnNum]);
};
}
</script>
<!-- FIXED - Solution 1 -->
<button id="btn-0">Button 1</button>
<button id="btn-1">Button 2</button>
<button id="btn-2">Button 3</button>
<script type="text/javascript">
const prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
// change var to let
for (let btnNum = 0; btnNum < prizes.length; btnNum++) {
// For each of our buttons, when the user clicks it...
document.getElementById(`btn-${btnNum}`).onclick = () => {
// Tell her what she's won!
alert(prizes[btnNum]);
};
}
</script>
<!-- FIXED - Solution 2 -->
<button id="btn-0">Button 1</button>
<button id="btn-1">Button 2</button>
<button id="btn-2">Button 3</button>
<script type="text/javascript">
const prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
const num = btnNum; // assign btnNum value to a variable in each loop
// For each of our buttons, when the user clicks it...
document.getElementById(`btn-${num}`).onclick = () => {
// Tell her what she's won!
alert(prizes[num]);
};
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment