OK, I'm sure this is a super simple question but other answers I found were a bit too complex for me to understand. I want to create a series of buttons, each sending an alert of the loop iteration it was created in. However, every button sends an alert of "5", the value of i after the loop is finished. How do I make a copy of i instead of accessing the actual value? Is this passing by value or reference?
<span id="buttons"></span>
<script>
var buttons = document.getElementById("buttons");
for (var i = 0; i < 5; i++) {
var btn = document.createElement("button");
btn.onclick = function(){alert(i);}
btn.innerHTML = "Button " + i;
buttons.appendChild(btn);
}
</script>