I will not talk much about it.
Let's take a look at two sections of code:
Copy codeThe Code is as follows:
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:
Copy codeThe Code is as follows:
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:
Copy codeThe 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:
Copy codeThe Code is as follows:
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 triggered.
// Similarly, the I value also changes at the end of the loop.
}, 'False ');
// The reason is that
// Here, elems [I] is a referenced element.
// But the I in the callback function is already after the end of the loop
// Changed to 8 (if the elems length is 8)
}
Copy codeThe Code is as follows:
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 difference here
// Although the I value becomes 8 after the loop ends
// However, the indexes enclosed in the closure are always locked.
// Keep it in 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.