js中用for循環事件綁定的小問題
阿新 • • 發佈:2018-02-22
hand 循環 ack ont char itl col charset scale
在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>
js中用for循環事件綁定的小問題