I'm writing a web app that has multiple buttons. I want each button to have almost the same behaviour, but i have a variable that needs to be different at each button.
I use jQuery. I have a loop that sets the functionality of each button, like in the following example:
for (var i = 1; i <= 7; i++) {
$("#button" + i).click(function() {
$("#result").html("Button " + i + " was clicked.");
});
}
When i click Button 4 i want to get displayed that button 4 was clicked, but it says that button 8 was clicked, because that is the value of i at the end of the loop. How can i solve this, so that i can have different results for every button?
EDIT: I solved it by using "let" instead of "var" for the i variable