In the most typical example, no matter which result is clicked, the above Code is the final value, because the click Event receives
First look at the Code:
Script var a = document. getElementsByTagName ('lil'); for (var I = 0, l = a. length; I
In the most typical example, no matter which result is clicked, the above Code 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 is executed, the variable I is the final value obtained by the loop, and the variable I in the closure is the value, therefore, the values 1, 2, and 3 are not displayed 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; I2. Save the current index value to the anonymous function itself.
Function fn () {var a = document. getElementsByTagName ("li"); for (var I = 0; I3. 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; I4. Add a closure to pass the current index value as a variable to the inner non-function.
Function fn () {var a = document. getElementsByTagName ("li"); for (var I = 0; I5. Add a closure to return a function as a response event.
Function fn () {var a = document. getElementsByTagName ("li"); for (var I = 0; I6. When using the Function object, you must note that the Function constructor creates a Function and uses the parameter as the parameter of the new Function during the script operation. Therefore, the execution efficiency is lower than that of the previous methods.
Function fn () {var a = document. getElementsByTagName ("li"); for (var I = 0; I7. Use Function object instances to generate closures.
Function fn () {var a = document. getElementsByTagName ("li"); for (var I = 0; I ". length; I ++) {a [I]. onclick = new Function ('alert ('+ I +'); // a Function instance is generated once new }}
This article is available at http://www.nowamagic.net/librarys/veda/detail/290.