aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/api/eventlistener/index.html
blob: 1f64dd72bc158417186c85b1994e5b065beb2ecf (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
85
86
87
88
89
90
91
---
title: EventListener
slug: Web/API/EventListener
tags:
  - DOM
  - 事件
  - 事件監聽
translation_of: Web/API/EventListener
---
<div>{{APIRef("DOM Events")}}</div>

<p><strong><code>EventListener</code></strong> 介面表示一個可以處理由 {{domxref("EventTarget")}} 物件分派事件的物件。</p>

<div class="note">
<p><strong>注意:</strong>基於相容舊版內容的需要, <code>EventListener</code> 可以接受一個函式及一個帶有 <code>handleEvent()</code> 屬性函式的物件。相關的<a href="#Example">範例</a>顯示在下方。</p>
</div>

<h2 id="屬性">屬性</h2>

<p><em>這個介面並不實作且不繼承任何屬性。</em></p>

<h2 id="方法">方法</h2>

<p><em>這個介面不繼承任何方法。</em></p>

<dl>
 <dt>{{domxref("EventListener.handleEvent()")}}</dt>
 <dd>一個可以在指定類型事件發生時被呼叫的函數。</dd>
</dl>

<h2 id="範例">範例</h2>

<h3 id="HTML">HTML</h3>

<pre class="brush: html">&lt;button id="btn"&gt;Click here!&lt;/button&gt;</pre>

<h3 id="JavaScript">JavaScript</h3>

<pre class="brush: js">const buttonElement = document.getElementById('btn');

// 透過提供回呼函數的方式對「click」事件新增處理器。
// 當元素被點選後會出現「Element clicked!」的彈出訊息。
buttonElement.addEventListener('click', function (event) {
  alert('Element clicked through function!');
});

// 基於相容性,一個帶有 `handleEvent` 的非函式物件可被視為處理函式。
buttonElement.addEventListener('click', {
  handleEvent: function (event) {
    alert('Element clicked through handleEvent property!');
  }
});
</pre>

<h3 id="結果">結果</h3>

<p>{{EmbedLiveSample('Example')}}</p>

<h3 id="檢閱相關">檢閱相關:</h3>

<ul>
 <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener</a></li>
</ul>

<h2 id="規格">規格</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">規格</th>
   <th scope="col">狀態</th>
   <th scope="col">註解</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('DOM WHATWG', '#callbackdef-eventlistener', 'EventListener')}}</td>
   <td>{{Spec2('DOM WHATWG')}}</td>
   <td>No change.</td>
  </tr>
  <tr>
   <td>{{SpecName('DOM2 Events', '#Events-EventListener', 'EventListener')}}</td>
   <td>{{Spec2('DOM2 Events')}}</td>
   <td>Initial definition.</td>
  </tr>
 </tbody>
</table>

<h2 id="瀏覽器相容性">瀏覽器相容性</h2>

<p>{{Compat("api.EventListener")}}</p>