首页 > 代码库 > js事件监听器用法实例详解

js事件监听器用法实例详解

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;

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<!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,谷歌和火狐
     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,谷歌和火狐
     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=http://www.mamicode.com/"测试" id="bindEvent">
  <input type="button" value=http://www.mamicode.com/"测试2" id="yuanEvent">
 </body>
</html

js事件监听器用法实例详解