Original link: http://www.cnblogs.com/pssp/p/5189345.html
Let me say a closed-bag usage scenario.
No closure versions are used
Window.onload = function () { var ul = document.getElementsByTagName ("ul") [0]; var li = ul.getelementsbytagname ("li"); for (Var i=0;i<li.length;i++) { Li[i].onclick = function () { console.log (i);//No matter how I point it back 6 } }}
The version of the closure is used
Window.onload = function () { var ul = document.getElementsByTagName ("ul") [0]; var li = ul.getelementsbytagname ("li"); for (Var i=0;i<li.length;i++) { (function (i) { Li[i].onclick = function () { console.log (i);// Click on first to return to the first few }} ) (i) }}
Comment Area:
for (Var i=0;i<li.length;i++) {
(function (i) {
Li[i].onclick = function () {
Console.log (i); Click on the first few to return to the first few
}
}) (i)
}
is not similar
for (Var i=0;i<li.length;i++) {
function aaa (i) {
Li[i].onclick = function () {
Console.log (i); Click on the first few to return to the first few
}
}
AAA (i);
}
Let the parameters in AAA (i) Get the I value and pass it in.
Related article: About binding an event in a for loop the print variable i is the last time.
The closure of the first knowledge in JS