普遍的写法:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="button" value="22"> <input type="button" value="22"> <input type="button" value="22"> <input type="button" value="22"> <div id="a" style="100px;height:100px;background:green;"></div> </body> </html> <script type="text/javascript"> window.onload = function () { var obtn = document.getElementsByTagName("input"); var i=0; for(i=0;i<obtn.length;i++){ aa(obtn[i]); } }; function aa(obj) { var count = 0; obj.onclick = function () { console.log(count++); }; } </script>
另一种写法:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="button" value="22"> <input type="button" value="22"> <input type="button" value="22"> <input type="button" value="22"> <div id="a" style="100px;height:100px;background:green;"></div> </body> </html> <script type="text/javascript"> window.onload = function () { var obtn = document.getElementsByTagName("input"); var i=0; for(i=0;i<obtn.length;i++){ (function (obj){ var count = 0; obj.onclick = function () { console.log(count++); }; })(obtn[i]); } }; </script>
注意aa(obtn[i])的写法转变为(fn)(obtn[i]),可以不用写函数名,把传入的参数放到方法的后面
繁琐的写法:
window.onload = function () { var obtn = document.getElementsByTagName("input"); var i=0; for(i=0;i<obtn.length;i++){ obtn[i].onclick = function (count) {//省去变量的声明 return function () { console.log(count++); } }(0); } };