I will not talk much about it.
Let's take a look at two sections of code:
var elems = document.getElementsByTagName('a');for (var i = 0; i < elems.length; i++) {alert(i); elems[i].addEventListener('click', function (e) { e.preventDefault(); alert('I am link #' + i); }, 'false');}
Let's look at another section:
var elems = document.getElementsByTagName('a');for (var i = 0; i < elems.length; i++) {(function(index){ elems[i].addEventListener('click', function (e) {e.preventDefault();alert('I am link #' + index);}, 'false');})(i);}The HTML code is as follows:
<body><a href = "#">a</a><a href = "#">a</a><a href = "#">a</a><a href = "#">a</a><a href = "#">a</a><a href = "#">a</a><a href = "#">a</a><a href = "#">a</a></body>
You can imagine the effects of the first and second sections of script code.
If you can see the difference, congratulations. At least I have been thinking for a long time before I can understand the mysteries.
Yes. You are not mistaken. The first code here, no matter which link you click, outputs I am link #8.
The second code is the result you really want. Why.
See the following code:
Var elems = document. getElementsByTagName ('A'); for (var I = 0; I <elems. length; I ++) {alert (I); elems [I]. addEventListener ('click', function (e) {e. preventDefault (); alert ('I am link #' + I); // note that the callback function starts only when it is triggered, here, the I value also changes at the end of the loop}, 'false '); // The reason is that // although the elems [I] Here is the referenced element //, the I in the callback function has been changed to 8 after the loop ends. (If the length of elems is 8 )}
Var elems = document. getElementsByTagName ('A'); for (var I = 0; I <elems. length; I ++) {(function (index) {elems [I]. addEventListener ('click', function (e) {e. preventDefault (); alert ('I am link #' + index) ;}, 'false') ;}) (I ); // here it is different // although the I value is changed to 8 after the loop ends // The index encapsulated in the closure is indeed always stored in locked. // memory. // To be accurate, the entire function is locked in the memory .}
Some knowledge about javascript closures may be required here.
The above code, thought for a long time, recorded to prevent forgetting.