currentTarget与target

currentTarget和target都是 2 级 DOM 事件标准定义的属性.

currentTarget:返回其事件监听器触发该事件的元素,是事件传播过程中经过的节点对象,它可能与target属性相同(目标阶段),也可能是target属性对应节点的祖先节点(捕获附页或冒泡阶段)。

target:返回触发此事件的元素(事件的目标节点),是直接触发事件的节点对象,是整个事件流的最底层的节点。

以下htm代码可以复制保存运行后可以帮助更好的理解:请留意27-38行handler函数

  1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title></title>
6 </head>
7 <body>
8 <input type="button" name="" value="placeholder" id="J_fmInput" />
9 <script type="text/javascript">
10 //事件监听
11 function addEvent(el, type, fn){
12
13 if (el.addEventListener) {
14 el.addEventListener(type, fn, false); //冒泡
15 }
16 else {
17 el['e' + fn] = function(){
18 fn.call(el, window.event);
19 }
20
21 el.attachEvent('on' + type, el['e' + fn]);
22
23 //alert(el.getAttribute('e' + fn)); el['e'+fn]是ie自定义属性
24 }
25 }
26 //handler
27 function handler(event){
28 var e = (event) ? event : window.event;
29 var itarget = (e.target) ? e.target : e.srcElement;
30 alert("target nodeName: " + itarget.nodeName);
31 alert("this nodeName: " + this.nodeName);
32 stopEvent(event);
33 if (!event.currentTarget) {
34 return false;
35 }
36 alert("currentTarget nodeName: " + e.currentTarget.nodeName);
37
38 }
39
40 //stopEvent
41 function stopEvent(event){
42 var e = (event) ? event : window.event;
43
44 if (e.stopPropagation) {
45 e.stopPropagation();
46 //e.preventDefault();
47 }
48 else {
49 e.cancelBubble = true;
50 //e.returnValue = false;
51 }
52 }
53 //封闭window.onload
54 function addLoadEvent(func){
55
56 var oldonload = window.onload;
57
58 if (typeof window.onload != 'function') {
59
60 window.onload = func;
61
62 }
63
64 else {
65
66 window.onload = function(){
67
68 if (oldonload) {
69
70 oldonload();
71
72 }
73
74 func();
75
76 }
77
78 }
79
80 }
81
82 function fmInput(){
83
84 var fmInput = document.getElementById("J_fmInput");
85
86 addEvent(fmInput, 'click', handler)
87
88 }
89
90 function fmDoc(){
91
92 addEvent(document, 'click', handler);
93
94 }
95
96 addLoadEvent(fmInput);
97 addLoadEvent(fmDoc);
98 </script>
99 </body>
100 </html>



posted @ 2011-10-11 22:00  wkylin  阅读(445)  评论(0编辑  收藏  举报