標籤:get bind 作用 函數 移除 tar javascrip 取消 head
IE下,event對象有srcElement屬性,但是沒有target屬性;
Firefox下,event對象有target屬性,但是沒有srcElement屬性.但他們的作用是相當的,即:
firefox 下的 event.target = IE 下的 event.srcElement
解決方案:使用obj = event.srcElement ? event.srcElement : event.target;
或:var evtTarget = event.target || event.srcElement;
?
| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Event</title> <script type="text/javascript"> function addEventHandler(target,type,func){ if(target.addEventListener){ //監聽IE9,Google和Firefox target.addEventListener(type, func, false); }else if(target.attachEvent){ target.attachEvent("on" + type, func); }else{ target["on" + type] = func; } } function removeEventHandler(target, type, func) { if (target.removeEventListener){ //監聽IE9,Google和Firefox target.removeEventListener(type, func, false); } else if (target.detachEvent){ target.detachEvent("on" + type, func); }else { delete target["on" + type]; } } var eventOne = function(){ alert("第一個監聽事件"); } function eventTwo(){ alert("第二個監聽事件"); } window.onload = function(){ var bindEventBtn = document.getElementById("bindEvent"); //監聽eventOne事件 addEventHandler(bindEventBtn,"click",eventOne); //監聽eventTwo事件 addEventHandler(bindEventBtn,"click",eventTwo ); //監聽本身的事件 addEventHandler(bindEventBtn,"click",function(){ alert("第三個監聽事件"); }); //取消第一個監聽事件 removeEventHandler(bindEventBtn,"click",eventOne); //取消第二個監聽事件 removeEventHandler(bindEventBtn,"click",eventTwo); } </script> </head> <body> <input type="button" value="測試" id="bindEvent"> <input type="button" value="測試2" id="yuanEvent"> </body> </html |
js事件監聽器用法執行個體詳解