JS Closed Package

Source: Internet
Author: User

1. Closures: Extend the scope of variables and save values that change at any time

Code:

<ul>

<li><a href= "#" > click on the No. 0 link </a></li>

<li><a href= "#" > click on the 1th link </a></li>

<li><a href= "#" > click on the 2nd link </a></li>

<li><a href= "#" > click on the 3rd link </a></li>

<li><a href= "#" > click on the 4th link </a></li>

</ul>

var links = document.getelementsbytagname (' a ');

Method 1:

function Closuretest (num) {

return function () {

Alert ("You clicked on the" + num + "link");

}

}

for (Var i=0;i<links.length;i++) {

Links[i].onclick = Closuretest (i);

}

Method 2:

for (Var i=0;i<links.length;i++) {

Links[i].onclick = (function (i) {

return function () {

Alert ("You clicked on the" + i + "link");

};

}) (i)

Method 3:

(function (i) {

Links[i].onclick = function () {

Alert ("You clicked on the" + i + "link");

//                 };

}) (i)

}

JS Closed 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.