In JS, if you use for loop event binding, you may encounter a small problem, see the first example below, regardless of which div is clicked, will pop up 3, that is, length.
Since this corresponds to the event binding, and does not bind the corresponding I, the value of I is the last value, that is, 3.
Example 1
<! DOCTYPE html>Div {width:100px; height:100px; background:red; Margin-bottom:3px; } </style> <script>window.onload=function () { varAdd_the_handlers =function(nodes) {vari; for(i = 0; i < nodes.length; i++) {Nodes[i].onclick=function(e) {alert (i); }; } }; varDIVs = document.getElementsByTagName (' div '); Add_the_handlers (divs); } </script> <body> <div></div> <div></div> <DIV></DIV&G T </body>Look at the following two examples, through the event binding, through the function call instead of the function definition for I and the event binding.
Example 2
<! DOCTYPE html>Div {width:100px; height:100px; background:red; Margin-bottom:3px; }</style><script>window.onload=function () { varAdd_the_handlers =function(nodes) {varHelper =function(index) {return function(e) {alert (index); }; }; vari; for(i = 0; i < nodes.length; i++) {Nodes[i].onclick=Helper (i); } }; varDIVs = document.getElementsByTagName (' div '); Add_the_handlers (divs); }</script><body> <div></div> <div></div> <div></div></body>& Lt;/html>
Example 3
<! DOCTYPE html>Div {width:100px; height:100px; background:red; Margin-bottom:3px; } </style> <script>window.onload=function () { varAdd_the_handlers =function(nodes) {vari; for(i = 0; i < nodes.length; i++) { (function(i) {Nodes[i].onclick=function() {alert (i); }; }) (i); } }; varDIVs = document.getElementsByTagName (' div '); Add_the_handlers (divs); } </script> <body> <div></div> <div></div> <DIV></DIV&G T </body>Small problem with a For loop event binding in JS