1. A simple example
First, from a classic error, there are a number of div on the page, we want to bind them an onclick method, and then have the following code
<ulID= "Divtest"> <Li>0</Li> <Li>1</Li> <Li>2</Li> <Li>3</Li> </ul><ulID= "DivTest2"> <Li>0</Li> <Li>1</Li> <Li>2</Li> <Li>3</Li> </ul>
Initial implementation:
var div = document.getElementById ("divtest"); var spans = div.getelementsbytagname ("li"); for (var i = 0; i < spans.length; i++) { function () { console.log (i); }
Result: The display is all 4, not the expected result, the desired 0,1,2,3,
Make the following changes to get the desired results
var div2 = document.getElementById ("DivTest2"); var spans2 = div2.getelementsbytagname ("li"); for (var i = 0; i < spans2.length; i++) { (function (num) { function () { console.log (num); } }) (i);
2. The reason
The first way, after the page load will be executed, when the value of I is 4, the judgment condition is not established, the for loop execution, but because each Li's OnClick method is an intrinsic function, so I was closed reference, memory can not be destroyed, I value will remain 4, It will not be recycled until the program changes it or all of the onclick functions are destroyed (by actively assigning the function null or page unloading).
So every time we click on Li, the onclick function looks for the value of I (the scope chain is a reference), a check equals 4, and then it shows to us.
The second way is to use an immediately executed function and create a layer of closure, the function declaration is placed in parentheses into an expression, followed by parentheses and parentheses is called, at this time I when the argument passed, the function is immediately executed, Num saves the value of I.
A preliminary understanding of JavaScript closures