In a html page, I need add event listeners for multiple buttons. Since the listener function for these buttons is very similar, I want to use a for-loop to finish the thing like this:
var button_list=[button1,button2];
// Let's say 'button1' and 'button2' are button elements.
var i=0;
for(var button of button_list) {
i+=1;
button.addEventListener('click', function() {
console.log(i);
// I want button1 to print '1' and button2 to print '2'
});
}
I want button1 to print 1 and button2 to print 2. But above code does not work since the variable i=2 eventually, so all clicked buttons will print 2. How can I solve the problem?