I feel like this question has already been answered, but I couldn't find it, so I'll ask it anyways.
I was playing with Javascript in HTML, and I decided to make a whole bunch of buttons using a loop. I wanted to assign a function to each one based on which it was. Here, I'll show you the script:
for (var i = 0; i < 6; i++) {
var button = document.createElement("button");
button.innerHTML = i;
button.className = "buttonclass";
button.onclick = function() {alert(i)};
var buttonDiv = document.getElementById("buttons");
buttonDiv.appendChild(button);
}
But when I click on any of the buttons, it returns a "6". I know where the problem is; I can't use simply {alert(i)}
. But what should I use instead?