I am trying to add onclick listeners to a list of buttons, the id of the buttons is in a range of 0-array length in this pattern btn1-btn2-btn3 and so on
I use a for loop to get the buttons by id and the event listeners against the fetched dom element:
for(var i =0; i<length; i++){
console.log("log 1: Adding listener for "+i);
document.getElementById("btn"+i).addEventListener("click", function(){
myFunc(i);
});
}
The Function
myFunc(i){
alert(i);
}
The Problem
No matter what button I click, I always get the last number in the for loop in the alert. I have checked and all buttons have different id's and the log 1 output is correct( ten logs 0-9). However log 2 output is the last number 10 no matter what button I click.
I want to know how I can pass the iterator(i) in the onclick listener. Any advice or suggestion will be agreat help to this newbie,Thanks!