面临的问题:
1.遍历form
2.动态添加事件处理函数(要求不能覆盖原有函数)
3.事件处理函数要求可以传递参数
解决方案:
1.document.forms[i].elements可以得到form所有元素。
2.不要使用 element.onclick=myclick 的形式,采用如下方法:
IE:element.attachEvent('onclick',function(){myclick()});
Firefox: element.addEventListener('click',function(){myclick()},false);
3.参照下面的函数function AttachEvent(type, target, handler, owner)
代码示例:
<HTML> <HEAD> <TITLE> test </TITLE> </HEAD> <BODY> <form name="form1"> <INPUT TYPE="button" value="button" onclick="old_click('hehe')" name="button1"> <br> <INPUT TYPE="TEXT" NAME="text1" id="ttt"> <br> <INPUT TYPE="text" NAME="text2"> <br> <TEXTAREA NAME="area1" ROWS="" COLS=""></TEXTAREA> <br> <INPUT TYPE="hidden" name="hidden1"> <br> <SELECT NAME="select1"> <option value="op1">op111</option> <option value="op2">op222</option> <option value="op3">op333</option> </SELECT> <br> <input type="radio" value="0" name="radio1">radio0 <input type="radio" value="1" name="radio1">radio1 <br> <input type="checkbox" name="checkbox1">checkbox1 </form> <SCRIPT LANGUAGE="JavaScript"> function AttachEvent(type, target, handler, owner){ var eventHandler = handler; if(owner){ // 在这里重新定义一个处理函数 eventHander = function(e){ handler.call(owner, e); } } if(window.attachEvent) target.attachEvent("on" + type, eventHander ); else target.addEventListener(type, eventHander, false); } function myclick(e){ alert(e); alert(this.name); } function myfocus(e){ alert("myfocus"); } function myblur(e){ alert("myblur"); } function mychange(e){ alert("mychange"); } function old_click(value){ alert(value); } for (i = 0; i< document.forms.length; i++){ var elements=document.forms[i].elements; for(j=0; j<elements.length; j++){ if(elements[j].type=="text"||elements[j].type=="textarea"){ AttachEvent("focus",elements[j],myfocus,elements[j]); AttachEvent("blur",elements[j],myblur,elements[j]); continue; } if(elements[j].type=="select-one"){ AttachEvent("change",elements[j],mychange,elements[j]); continue; } AttachEvent("click",elements[j],myclick,elements[j]); } } </SCRIPT> </BODY> </HTML> |