<div id="mydiv0"></div>
<div id="mydiv1"></div>
<div id="mydiv2"></div>
var myArray = [
document.getElementById("mydiv0"),
document.getElementById("mydiv1"),
document.getElementById("mydiv2")
];
function myFunction(x){
alert("my number is " + x);
}
for(var i = 0; i < myArray.length; i++){
myArray[i].addEventListener("click", function(){myFunction(i);});
}
I want to attach event listener to each element in myArray. When clicked, an alert message should be displayed showing numbers 0,1 and 2 for mydiv0, mydiv1 and mydiv2 respectively. I tried using for loop as seen in the example above, but no matter which div I click on, I get "my number is 3" message. Is there a way to pass the different values of variable i as a parameter of myFunction?