blob: 13b1862083d3856c5bf69885055c091184567c55 (
plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
---
title: Event.target
slug: Web/API/Event/target
translation_of: Web/API/Event/target
---
<p>{{ApiRef("DOM")}}</p>
<p>指向最初觸發事件的 DOM 物件。與 {{domxref("event.currentTarget")}} 屬性不同的是,<code>event.currentTarget</code> 屬性總會指向目前於冒泡或捕捉階段正在處理該事件之事件處理器所註冊的 DOM 物件,而 <code>event.target</code> 屬性則是永遠指向觸發事件的 DOM 物件。</p>
<h2 id="語法">語法</h2>
<pre class="syntaxbox">theTarget = event.target</pre>
<h2 id="範例">範例</h2>
<p>The <code>event.target</code> property can be used in order to implement <strong>event delegation</strong>.</p>
<pre class="brush: js">// Make a list
var ul = document.createElement('ul');
document.body.appendChild(ul);
var li1 = document.createElement('li');
var li2 = document.createElement('li');
ul.appendChild(li1);
ul.appendChild(li2);
function hide(e){
// e.target refers to the clicked <li> element
// This is different than e.currentTarget which would refer to the parent <ul> in this context
e.target.style.visibility = 'hidden';
}
// Attach the listener to the list
// It will fire when each <li> is clicked
ul.addEventListener('click', hide, false);
</pre>
<h2 id="規範">規範</h2>
<table class="standard-table">
<tbody>
<tr>
<th>Specification</th>
<th>Status</th>
<th>Comment</th>
</tr>
<tr>
<td>{{SpecName("DOM WHATWG", "#dom-event-target", "Event.target")}}</td>
<td>{{Spec2("DOM WHATWG")}}</td>
<td> </td>
</tr>
<tr>
<td>{{SpecName("DOM4", "#dom-event-target", "Event.target")}}</td>
<td>{{Spec2("DOM4")}}</td>
<td> </td>
</tr>
<tr>
<td>{{SpecName("DOM2 Events", "#Events-Event-target", "Event.target")}}</td>
<td>{{Spec2("DOM2 Events")}}</td>
<td>Initial definition</td>
</tr>
</tbody>
</table>
<h2 id="瀏覽器相容性">瀏覽器相容性</h2>
{{Compat("api.Event.target")}}
<h2 id="Compatibility_notes">Compatibility notes</h2>
<p>On IE 6-8 the event model is different. Event listeners are attached with the non-standard {{domxref('EventTarget.attachEvent')}} method. In this model, the event object has a {{domxref('Event.srcElement')}} property, instead of the <code>target</code> property, and it has the same semantics as <code>event.target</code>.</p>
<pre class="brush: js">function hide(e) {
// Support IE6-8
var target = e.target || e.srcElement;
target.style.visibility = 'hidden';
}
</pre>
<h2 id="參見">參見</h2>
<ul>
<li><a href="/en-US/docs/Web/API/Event/Comparison_of_Event_Targets">Comparison of Event Targets</a></li>
</ul>
|