The closure of the first knowledge in JS

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.