JS anonymous function Closure

Source: Internet
Author: User
No pop-up box

 
<Script language = "JavaScript" type = "text/JavaScript"> function start () {var nid = document. getelementsbytagname ("Li"); NID. onclick = function () {alert ("4") ;}} window. onload = start; </SCRIPT>

 

In this way, a dialog box is displayed.

 
<Script language = "JavaScript" type = "text/JavaScript"> function start () {var nid = document. getelementsbytagname ("Li"); NID. onclick = (function () {alert ("4") ;}) ()} window. onload = start; </SCRIPT>

 

After running, no matter which Li you click, alert prompts "4 ".

This is a note:

The closure allows the inner function to reference a variable in the parent function, but the variable is the final value. The variable I referenced by the closure is the value after the end of the loop.

<Script language = "JavaScript" type = "text/JavaScript"> var li = document. getelementsbytagname ("Li"); For (VAR I = 0; I <li. length; I ++) {Li [I]. onclick = function () {alert (I) ;}</SCRIPT>

 

Use closures to solve

<Script language = "JavaScript" type = "text/JavaScript">
VaR li = Document. getelementsbytagname ("Li ");
For (VAR I = 0; I <li. length; I ++ ){
(Function (INDEX ){
Li [Index]. onclick = function () {alert (INDEX );}
}) (I );
}
</SCRIPT>

 

 

 

Note: "clicked" is displayed first, and then "also clicked" is displayed"

 
<SCRIPT> var fnclick1 = function () {alert ("clicked") ;}; var fnclick2 = function () {alert ("also clicked ");}; vaR odiv = document. getelementbyid ("Div"); odiv. attachevent ("onclick", fnclick2); odiv. attachevent ("onclick", fnclick1); </SCRIPT>

"Also clicked" is displayed first, and then "clicked" is displayed"

 
VaR odiv = Document. getelementbyid ("Div"); odiv. attachevent ("onclick", fnclick1); odiv. attachevent ("onclick", fnclick2 );

 

 

. Onclick is followed by the first execution
The Dom interpretation of the events that attachevent is involved is random.
However, in actual testing, ie is followed by binding and FF is followed by binding.

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.