Not much to say.
Let’s look at two pieces of code first:
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');
}
Look at it again:
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);
}
HTML code is as follows:
You can imagine the effect of the two script codes before and after.
If you can see the difference in effect, congratulations. At least I thought about it for a long time before I understood the mystery behind it.
Yes. You read that right, the first piece of code here, no matter which link you click, the output is I am link # 8.
The second piece of code is the result you really want, then Why.
Look at the code below:
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 here only triggers
//Same, the value of i here also changes at the end of the loop
}, 'false');
//The reason is
//Although elems[i] here is a referenced element
//but i in the callback function has 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);
//This is different
//Although the value of i becomes 8 after the loop ends
//But the index encapsulated in the closure is indeed locked.
//Always saved in memory.
//To be precise, the entire function should be locked in memory.
}
Some knowledge of javascript closures may be required here.
I have thought about the above code for a long time and recorded it to prevent forgetting.