JAVASCIRPT Closure Package

Source: Internet
Author: User

I saw a question a while ago

<P>P1</P><P>P2</P><P>P3</P><P>P4</P><P>P5</P><P>P6</P>
<script>function  clickp () {var a = document.getElementsByTagName ("P");      for (var i=0;i<a.length;i++) {            function() {                    alert (i);}                ;}        } CLICKP (); </script>

Click All P tag pop-up tips are 6, if improved CLICKP () so that click P to indicate the corresponding index 1, 2, 3 ....

Because the Click event has not yet been triggered, the loop is complete, so no matter which p is prompt 6

/*to modify the above method, click P to eject the corresponding ordinal number * The principle of creating closures is: Do not reference the loop variable!        * What if you must refer to the loop variable in the closure??? * method is to create a function that passes the loop variable as a function parameter*/                        functionClickp () {varA = document.getElementsByTagName ("P");  for(vari=0;i<a.length;i++){                            varfn =function(n) {A[n].onclick=function() {alert (n+1);                    }} fn (i); }} clickp ();

JAVASCIRPT Closure Package

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.