Code
< Ul >
< Li > 1111 < / LI>
< Li > 2222 < / LI>
< Li > 3333 < / LI>
< / Ul>
< Script >
VaR A = Document. getelementsbytagname ( ' Li ' );
For ( VaR I = 0 , L = A. length; I < L; I ++ ){
A [I]. onclick = Function (){
Alert (I)
}
}
< / SCRIPT>
A classic example:CodeNo matter which result you click is the final value, because the function received by the click event forms a closure, the I in the closure is only a reference to the variable I in the external function, when FN execution is complete, variable I is the final value obtained by the loop, and variable I in the closure is the value, so 1, 2.3 will not pop up in sequence.
Solution:
1) add custom attributes for each element to save the current index value.
Function FN (){
VaR A = Document. getelementsbytagname ( "Li " );
For ( VaR I = 0 ; I < A. length; I ++ ){
A [I]. I = I;
A [I]. onclick = Function (){
Alert ( This . I );
}
}
}
2) Save the current index value to the anonymous function itself.
Function FN (){
VaR A = Document. getelementsbytagname ( " Li " );
For ( VaR I = 0 ; I < A. length; I ++ ){
(A [I]. onclick = Function (){
Alert (arguments. callee. I );
}). I = I;
}
}
3) Add a closure to pass the current index value to the internal function as a function parameter.
Function FN (){
VaR A = Document. getelementsbytagname ( " Li " );
For ( VaR I = 0 ; I < A. length; I ++ ){
( Function (ARG ){
A [I]. onclick = Function (){
Alert (ARG );
};
}) (I ); // Call Parameters
}
}
4) Add a closure to pass the current index value as a variable to the inner non-function.
Code
Function FN (){
VaR A = Document. getelementsbytagname ( " Li " );
For ( VaR I = 0 ; I < A. length; I ++ ){
( Function (){
VaR Index = I; // Local variables during call
A [I]. onclick = Function (){
Alert (INDEX );
}
})();
}
}
5) Add a closure to return a function as a response event.
Code
Function FN (){
VaR A = Document. getelementsbytagname ( " Li " );
For ( VaR I = 0 ; I < A. length; I ++ ){
A [I]. onclick = Function (ARG ){
Return Function (){ // Returns a function.
Alert (ARG );
}
} (I );
}
}
6) when using the function object, it should be noted that the function constructor creates a function and uses the parameter as the parameter of the new function during script running, so the execution efficiency is lower than that of the previous methods.
Function FN (){
VaR A = Document. getelementsbytagname ( " Li " );
For ( VaR I = 0 ; I < A. length; I ++ ){
A [I]. onclick = Function ( ' Alert ( ' + I + ' ) ' )
}
}
7) use function object instances to generate closures.
Function FN (){
VaR A = Document. getelementsbytagname ( " Li " );
For ( VaR I = 0 ; I < A. length; I ++ ){
A [I]. onclick = New Function ( ' Alert (' + I +' )' ); // New generates a function instance at a time.
}
}