Closure in Loop

Source: Internet
Author: User

The concept of closure has never been quite understood. So is now...

 

 

A few days ago, I participated in the online examination of Alibaba's front-end. I had the following question:

The following code is available:

<p>p1</p><p>p2</p><p>p3</p><p>p4</p><p>p5</p>var ps = document.getElementsByTagName(‘p‘);for(var i = 0; i < ps.length; i++) {    ps[i].onclick = function() {        alert(i);    }}

 

Write the running result of the above Code. If you want to output 0 ~ Length-1: there are at least two ways to modify the code.

 

At first, I didn't know what I was taking the test. I found this problem very common only when I was reading books these two days ~~

 

The above code is displayed.

WhenalertWhen called,AnonymousFunction persistence for external variablesi.forThe loop has ended,iIs modified5.

That is to say, each P element is bound with a click event, that is, alert (I), but the value of I has become 5 after the end of the loop, so each click is 5.

 

In this case, we need to copy the current I in each loop to bring up, at a time.

Method 1 is to use the immediate execution function:

for(var i = 0; i < ps.length; i++) {    (function(e) {        ps[i].onclick = function() {            alert(e);        }    })(i);}

External anonymous functions are executed immediately andiAs its parameter, the functioneThe variable hasi.

When the anonymous function that is passed to a click is executed, it haseAnd the value isNoChanged cyclically.

Method 2: return a function from an anonymous function:

for(var i = 0; i < ps.length; i++) {    ps[i].onclick = (function(e) {        return function() {            alert(e);        }    })(i);}

 

Reference: http://bonsaiden.github.io/JavaScript-Garden/zh/#function.closures

Http://javascript.ruanyifeng.com/grammar/function.html#toc18

 

In fact, I am not quite familiar with it, but I wrote the following method. I don't know if it is a regular army...

Set a parent Div on the outer layer, and add a click event on the div.

<div>    <p>p1</p>    <p>p2</p>    <p>p3</p>    <p>p4</p>    <p>p5</p></div>var div = document.getElementsByTagName(‘div‘)[0];var ps = document.getElementsByTagName(‘p‘);div.onclick = function(e) {    for(var i = 0; i < ps.length; i++) {        if(e.target == ps[i]) {            alert(i);        }    }}

 

Closure in Loop

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.