<div>div 0</div>
<div>div 1</div>
<script>
var div = document.getElementsByTagName ("div");
for (var i = 0; i < div.length i++) {
div[i].addeventlistener ("click", Function () {
alert ("div #" + i +) is CLI Cked. ")
});
}
</script>
When you click on Div 0 o'clock, the pop-up is shown in the following figure:
This is a classic closure problem, because of the closure, the variable i in the anonymous function in AddEventListener keeps the reference to the external variable I (that is, whether it is an anonymous function or a function outside of an anonymous function, the value of the variable i is changed, it will change), so when the loop ends, I The value is the last value, which is 2.
The solution to the problem is to add the immediate execution function so that the variable i in the anonymous function is disconnected from the reference to the variable I of the external function.
<div>div 0</div>
<div>div 1</div>
<script>
var div = document.getElementsByTagName ("div");
var div = document.getelementsbytagname ("div");
for (var i = 0; i < div.length i++) {
(function (index) {
Div[index].addeventlistener ("click", Function () {
alert ("div #" + index + "was clicked!")
})
(i);
}
</script>
When you click on Div 0 o'clock, the value we expect will pop up.