概述
addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, thedocument itself, a window, or an XMLHttpRequest.
To register more than one event listener for the target, call addEventListener() for the same target but with different event types or capture parameters.
语法
target.addEventListener(type, listener[, useCapture]);
target.addEventListener(type, listener[, useCapture, aWantsUntrusted 非标准]); // Gecko/Mozilla only
- A string representing the event type to listen for.
-
The object that receives a notification when an event of the specified type occurs. This must be an object implementing the
EventListenerinterface, or simply a JavaScript function. -
If
true,useCaptureindicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registeredlistenerbefore being dispatched to anyEventTargetbeneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See DOM Level 3 Events for a detailed explanation. Note that this parameter is not optional in all browser versions. If not specified,useCaptureisfalse. -
If
true, the event can be triggered by untrusted content. See Interaction between privileged and non-privileged pages.
type
listener
useCapture
可选
aWantsUntrusted
非标准
useCapture became optional only in more recent versions of the major browsers; for example, it was not optional prior to Firefox 6. You should provide that parameter for broadest compatibility.
例子
|
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
|
<
html
>
<
head
>
<
title
>DOM Event Example</
title
>
<
style
type
=
"text/css"
>
#t { border: 1px solid red }
#t1 { background-color: pink; }
</
style
>
<
script
type
=
"application/javascript"
>
// Function to change the content of t2
function modifyText() {
var t2 = document.getElementById("t2");
t2.firstChild.nodeValue = "three";
}
// Function to add event listener to t
function load() {
var el = document.getElementById("t");
el.addEventListener("click", modifyText, false);
}
document.addEventListener("DOMContentLoaded", load, false);
</
script
>
</
head
>
<
body
>
<
table
id
=
"t"
>
<
tr
><
td
id
=
"t1"
>one</
td
></
tr
>
<
tr
><
td
id
=
"t2"
>two</
td
></
tr
>
</
table
>
</
body
>
</
html
>
|
In the above example, modifyText() is a listener for click events registered using addEventListener(). A click anywhere on the table will bubble up to the handler and run modifyText().
If you want to pass parameters to the listener function, you have to use an anonymous function.
|
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
|
<
html
>
<
head
>
<
title
>DOM Event Example</
title
>
<
style
type
=
"text/css"
>
#t { border: 1px solid red }
#t1 { background-color: pink; }
</
style
>
<
script
type
=
"text/javascript"
>
// Function to change the content of t2
function modifyText(new_text) {
var t2 = document.getElementById("t2");
t2.firstChild.nodeValue = new_text;
}
// Function to add event listener to t
function load() {
var el = document.getElementById("t");
el.addEventListener("click", function(){modifyText("four")}, false);
}
</
script
>
</
head
>
<
body
onload
=
"load();"
>
<
table
id
=
"t"
>
<
tr
><
td
id
=
"t1"
>one</
td
></
tr
>
<
tr
><
td
id
=
"t2"
>two</
td
></
tr
>
</
table
>
</
body
>
</
html
>
|
备注
为什么要使用addEventListener?
addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:
- It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well even if other libraries/extensions are used.
- It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
- It works on any DOM element, not just HTML elements.
The alternative, older way to register event listeners is described below.
Adding a listener during event dispatch
If an EventListener is added to an EventTarget while it is processing an event, it will not be triggered by the current actions but may be triggered during a later stage of event flow, such as the bubbling phase.
Multiple identical event listeners
If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause theEventListener to be called twice, and since the duplicates are discarded, they do not need to be removed manually with the removeEventListener method.
The value of this within the handler
It is often desirable to reference the element from which the event handler was fired, such as when using a generic handler for a series of similar elements. When attaching a function using addEventListener() the value of this is changed—note that the value of this is passed to a function from the caller.
In the example above, the value of this within modifyText() when called from the click event is a reference to the table 't'. This is in contrast to the behavior that occurs if the handler is added in the HTML source:
|
1
2
|
<
table
id
=
"t"
onclick
=
"modifyText();"
>
. . .
|
The value of this within modifyText() when called from the onclick event will be a reference to the global (window) object.
Function.prototype.bind() method, which lets you specify the value that should be used as
this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Note, however, that you'll need to keep a reference to the listener around so you can later remove it.
旧版Internet Explorer 的 attachEvent方法
In Internet Explorer versions prior to IE 9, you have to use attachEvent rather than the standard addEventListener. To support IE, the example above can be modified to:
|
1
2
3
4
5
|
if
(el.addEventListener) {
el.addEventListener(
'click'
, modifyText,
false
);
}
else
if
(el.attachEvent) {
el.attachEvent(
'onclick'
, modifyText);
}
|
There is a drawback to attachEvent, the value of this will be a reference to the window object instead of the element on which it was fired.
注册事件侦听器的传统方法
addEventListener() was introduced with the DOM 2 Events specification. Before then, event listeners were registered as follows:
|
1
2
3
4
5
6
7
|
// Pass a function reference — do not add '()' after it, which would call the function!
el.onclick = modifyText;
// Using a function expression
element.onclick =
function
() {
// ... function logic ...
};
|
This method replaces the existing click event listener(s) on the element if there are any. Similarly for other events and associated event handlers such as blur (onblur),keypress (onkeypress), and so on.
Because it was essentially part of DOM 0, this method is very widely supported and requires no special cross–browser code; hence it is normally used to register event listeners dynamically unless the extra features of addEventListener() are needed.
内存问题
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
var
i;
var
els = document.getElementsByTagName(
'*'
);
// Case 1
for
(i=0 ; i<els.length ; i++){
els[i].addEventListener(
"click"
,
function
(e){
/*do something*/
},
false
});
}
// Case 2
function
processEvent(e){
/*do something*/
}
for
(i=0 ; i<els.length ; i++){
els[i].addEventListener(
"click"
, processEvent,
false
});
}
|
In the first case, a new (anonymous) function is created at each loop turn. In the second case, the same previously declared function is used as an event handler. This results in smaller memory consumption. Moreover, in the first case, since no reference to the anonymous functions is kept, it is not possible to callelement.removeEventListener because we do not have a reference to the handler, while in the second case, it's possible to domyElement.removeEventListener("click", processEvent, false).
浏览器兼容性
- Desktop
- Mobile
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support | 1.0 | 1.0 (1.7 or earlier) | 9.0 | 7 | 1.0 |
useCapture made optional | 1.0 | 6.0 | 9.0 | 11.60 | (Yes) |
Gecko 备注
- Prior to Firefox 6, the browser would throw if the
useCaptureparameter was not explicitly <font face="'Courier New', 'Andale Mono', monospace">false</font>. Prior to Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6),addEventListener()would throw an exception if thelistenerparameter wasnull; now the method returns without error, but without doing anything.
WebKit 备注
- Although WebKit has explicitly added
[optional]to theuseCaptureparameter fairly recently, it had been working before the change. The new change landed in Safari 5.1 and Chrome 13.

本文详细介绍了如何使用DOM2 Events规范中的addEventListener()方法注册事件监听器,包括其语法、用法、特点及浏览器兼容性。通过具体实例展示了如何在网页中实现点击事件的响应,并讨论了addEventListener()相对于传统attachEvent方法的优势,如事件捕获与冒泡阶段的控制、对不同DOM元素的支持等。此外,文章还对比了两种注册事件监听器的方法在内存管理上的差异,并提供了代码示例以帮助开发者更好地理解和应用这一核心Web技术。
638

被折叠的 条评论
为什么被折叠?



