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