在js中,如果用for循环进行事件绑定,可能会遇到一点小问题,看下面第一个示例,无论点击哪个div,都会弹出3,即length。
因为这相当于事件绑定的同时,并没有把所对应的i进行一起绑定,i的值是最后一个值,即3。
示例1
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div { width: 100px; height: 100px; background: red; margin-bottom: 3px; } </style> <script> window.onload = function () { var add_the_handlers = function (nodes) { var i; for (i = 0; i < nodes.length; i++) { nodes[i].onclick = function (e) { alert(i); }; } }; var divs = document.getElementsByTagName(‘div‘); add_the_handlers(divs); } </script> <body> <div></div> <div></div> <div></div> </body> </html>
再看下面两个例子,通过事件绑定的同时,通过函数调用而不是函数定义进行i与事件的绑定。
示例2
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <style> div { width: 100px; height: 100px; background: red; margin-bottom: 3px; } </style> <script> window.onload = function () { var add_the_handlers = function (nodes) { var helper = function (index) { return function (e) { alert(index); }; }; var i; for (i = 0; i < nodes.length; i++) { nodes[i].onclick = helper(i); } }; var divs = document.getElementsByTagName(‘div‘); add_the_handlers(divs); } </script> <body> <div></div> <div></div> <div></div> </body> </html>
示例3
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div { width: 100px; height: 100px; background: red; margin-bottom: 3px; } </style> <script> window.onload = function () { var add_the_handlers = function (nodes) { var i; for (i = 0; i < nodes.length; i++) { (function (i) { nodes[i].onclick = function () { alert(i); }; })(i); } }; var divs = document.getElementsByTagName(‘div‘); add_the_handlers(divs); } </script> <body> <div></div> <div></div> <div></div> </body> </html>