Add the following script code:
- <script>
- var list_obj = document.getelementsbytagname (' Li ');
- for (var i = 0; I <= list_obj.length; i++) {
- List_obj[i]. onclick = function () {
- alert (i);
- }
- }
- </Script>
After running, the strange discovery no matter what click on the Li tag, alert out is the last content, 5
The following analysis: Because the event handler specified to List_obj[i].onclick in the For loop, the onclick anonymous function is called when the For Loop executes (when the user clicks the link). When called, the variable I needs to be evaluated, the resolver is first found inside the event handler, but I is not defined. Then, to the outside of the method to find, there is a definition, but the value of I is 4 (only I greater than 4 will stop execution for the For loop). Therefore, the value is obtained-this is the result of the closure (anonymous function) to use the variables in its outer scope. Also, this is due to the fact that the anonymous function itself cannot pass parameters (and therefore cannot maintain its scope).
Now the reason is to know, how to avoid this situation?
Now that we know that the function calls the external variable, it forms a closure, and the variables are affected elsewhere, so we
Now all you have to do is build a closure that is accessible only to itself, and save the variables that are used only by itself.
Building a closure is simple and the code is as follows:
Way One:
[JavaScript]View PlainCopy
- var list_obj = document.getelementsbytagname (' Li ');
- for (var i = 0; I <= list_obj.length; i++) {
- <span style="White-space:pre" > </span>list_obj[i].onclick = (function (i) { //outer function
- <span style="White-space:pre" > </span>return function () { //inner function
- <span style="White-space:pre" > </span>alert (i);
- <span style="White-space:pre" > </span>};
- <span style="White-space:pre" > </span>}) (i);
- }*
Way two:
[JavaScript]View PlainCopy
- var list_obj = document.getelementsbytagname (' Li ');
- for (var i = 0; I <= list_obj.length; i++) {
- (function (i) {
- //var p = i
- List_obj[i].onclick = function () {
- alert (i);
- }
- }) (i);
- }
JS closure causes the loop to add an event to the button always executes the last