🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 事件探析 ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>test</title> <script src="https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/js/lib/jquery-1-cc52697ab1.10.2.js"></script> <style> .box { margin: 10px 0; background: red; height: 100px; } </style> </head> <body> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <script> boxs = document.getElementsByClassName('box'); var len = boxs.length; // 一:为什么这种循环绑定事件,最后弹出都是4 // for (var i = 0; i < len; i++) { // boxs[i].onclick = function() { // alert(i); // }; // } // 事件绑定还是和上面一样,i 是局部变量了,但还是不符合我们常规理解预期的 // function test() { // for (var i = 0; i < len; i++) { // boxs[i].onclick = function () { // var i2 = i; // console.log(i2) // }; // } // } // test(); // function test() { // for (var i = 0; i < len; i++) { // $(boxs[i]).click(function() { // console.log(i); // }); // } // } // test(); // function test() { // $('.box').each(function(index, el) { // $(el).click(function() { // console.log(index); // }); // }); // } // test(); // function test() { // for (var i = 0; i < len; i++) { // (function () { // boxs[i].onclick = function () { // console.log(i) // }; // })(); // } // } // test(); function test() { for (var i = 0; i < len; i++) { setTimeout(function () { // Cannot set property 'onclick' of undefined // in boxs[4] undefined boxs[i].onclick = function () { console.log(i) }; }, 10); } } test(); </script> </body> </html> ```