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.