This is not a duplicate question.
I have a list of buttons that I want to pass a unique value into when it's dynamically generated as shown below.
Expected outcome: I want the alert to show "Hello World" plus Index Of The Button when it was generated.
Current Outcome: alert is constantly showing "Hello World 20". 20 being the last index of the for loop.
<!DOCTYPE html>
<html>
<body onload="genManyBtns()">
<p>Click the button to show an Alert Corresponding to it's Index</p>
<script>
function genManyBtns() {
for (var i = 0; i < 20; i++) {
var btn = document.createElement("BUTTON");
btn.innerHTML = "CLICK ME";
btn.onclick = function() {
alert("Hello World " + i)
};
document.body.appendChild(btn);
}
}
</script>
</body>
</html>