日期:2014-05-18 浏览次数:20744 次
<body> ... <input type="button" name="mybutton"> <input type="button" name="mybutton"> ... </body> <script> var temp = ""; window.onload = function() { for (i=0; i < document.getElementsByName("mybutton").length; i++) { temp = i; document.getElementsByName("mybutton")[i].onclick=function() {func(temp)}; // 为每个button添加响应事件 } } function func(value) { alert(value); } </script> <!--这种情况下,无论点击哪一个按钮,都会输出1,因为在for循环中,i变为2时便跳出了,所以temp最终值为1。但是我本意显然是想当按下两个按钮时一个跳出0,一个跳出1。而现在它全部用temp的最终值(也就是1)处理,那是否意味着函数在传递参数时,传递的是指针,那如何解决这个问题、达到我要的效果呢?谢谢~-->
<body> <input type="button" name="mybutton" para=""> <input type="button" name="mybutton" para=""> <script> window.onload = function() { for (i=0; i < document.getElementsByName("mybutton").length; i++) { document.getElementsByName("mybutton")[i].para=i; document.getElementsByName("mybutton")[i].onclick=function() {func(this.para);}; // 为每个button添加响应事件 } } function func(value) { alert(value); } </script> </body>
------解决方案--------------------
<!doctype html public "-//w3c//dtd html 4.0 transitional//en"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gbk" /> <title> new document </title> </head> <script type="text/javascript"> var Event = {} Event = { getEventHandler : function(obj, fun) { var args = []; obj = obj || window; for(var i = 2; i < arguments.length; i++) { args.push(arguments[i]); } return function() { fun.apply(obj, args); }; } } function func(value) { alert(value); } window.onload = function() { var btns = document.getElementsByName('mybutton'); for(var i = 0; i < btns.length; i++) { btns[i].onclick = Event.getEventHandler(window, func, i); } } </script> <body> <input type="button" name="mybutton" value="test"><br/> <input type="button" name="mybutton" value="test"> </body> </html>