The Web platform provides several ways to be notified of
DOM 事件
. Two common approaches are
addEventListener()
and the specific
on
event
handlers.
This page focuses on how the latter work.
on
event
handlers are properties on certain DOM elements to manage how that element reacts to events. Elements can be interactive (links, buttons, images, forms, and so forth) or non-interactive (such as the base
<body>
element). Events are actions like:
on
event
handler is usually named with the event it reacts to, like
on
click
,
on
keypress
,
on
focus
,等。
You can specify an
on
<…>
event handler for a particular event (such as
click
) for a given object in different ways:
on
<eventtype>
:
<button
onclick="handleClick()"
>
,
document.querySelector("button")
.onclick = function(event) { … }
.
An
on
event
event handler property serves as a placeholder of sorts, to which a single event handler can be assigned. In order to allow multiple handlers to be installed for the same event on a given object, you can call its
addEventListener()
method, which manages a list of handlers for the given event on the object. A handler can then be removed from the object by calling its
removeEventListener()
函数。
When an event occurs that applies to an element, each of its event handlers is called to allow them to handle the event, one after another. You don't need to call them yourself, although you can do so in many cases to easily simulate an event taking place. For example, given a button object
myButton
, you can do
myButton.onclick(myEventObject)
to call the event handler directly. If the event handler doesn't access any data from the event object, you can leave out the event when calling
onclick()
.
This continues until every handler has been called, unless one of the event handlers explicitly halts the processing of the event by calling
stopPropagation()
on the event object itself.
Event handlers can also be set with properties on non-element objects that generate events, like
window
,
document
,
XMLHttpRequest
, and others. For example, for the
progress
event on instances of
XMLHttpRequest
:
const xhr = new XMLHttpRequest();
xhr.onprogress = function() { … };
HTML elements have attributes named
on
event
which can be used to register a handler for an event directly within the HTML code. When the element is built from the HTML, the value of its
on
event
attributes are copied to the DOM object that represents the element, so that accessing the attributes' values using JavaScript will get the value set in the HTML.
Further changes to the HTML attribute value can be done via the
setAttribute
method; Making changes to the JavaScript property will have no effect.
给定此 HTML 文档:
<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
<a onclick="log('Click!')">these three words</a>.
</p>
<div></div>
Then this JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the JavaScript object's property.
let logElement = document.querySelector('div');
let el = document.querySelector("a");
function log(msg) { logElement.innerHTML += `${msg}<br>` };
function anchorOnClick(event) { log("Changed onclick handler") };
// Original Handler
log(`Element's onclick as a JavaScript property: <code> ${el.onclick.toString()} </code>`);
//Changing handler using .onclick
log('<br>Changing onclick handler using <strong> onclick property </strong> ');
el.onclick = anchorOnClick;
log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
log(`But the HTML attribute is unchanged: <code> ${el.getAttribute("onclick")} </code><br>`);
//Changing handler using .setAttribute
log('<hr/><br> Changing onclick handler using <strong> setAttribute method </strong> ');
el.setAttribute("onclick", 'anchorOnClick(event)');
log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
log(`Now even the HTML attribute has changed: <code> ${el.getAttribute("onclick")} </code><br>`);
For historical reasons, some attributes/properties on the
<body>
and
<frameset>
elements instead set event handlers on their parent
Window
object. (The HTML specification names these:
onblur
,
onerror
,
onfocus
,
onload
,和
onscroll
)。
When the event handler is specified as an HTML attribute , the specified code is wrapped into a function with the following parameters :
event
— for all event handlers except
onerror
.
event
,
source
,
lineno
,
colno
,和
error
为
onerror
event handler. Note that the
event
parameter actually contains the error message as a string.
When the event handler is invoked, the
this
keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see
the
this
keyword documentation
.
The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event; for details, see "The event handler processing algorithm" in the HTML specification .
TBD (non-capturing listener)
术语 event handler may refer to:
on…
attributes in HTML or properties in Web APIs, such as
<button onclick="alert(this)">
or
window.onload = function() { … }
.
When discussing the various methods of listening to events:
EventTarget.addEventListener()
on…
attributes or properties
| 规范 | 状态 | 注释 |
|---|---|---|
|
HTML 实时标准
在该规范中的 event handlers 定义。 |
实时标准 | |
|
HTML5
在该规范中的 event handlers 定义。 |
推荐 |
You can detect the presence of an event handler property with the JavaScript
in
operator. For example:
if ("onsomenewfeature" in window) {
/* do something amazing */
}
You can't set or access the values of any IDL-defined attributes on DOM prototype objects. That means you can't, for example, change
Window.prototype.onload
. In the past, event handlers (
onload
, etc.) weren't implemented as IDL attributes in Gecko, so you were able to do this for those. Now you can't. This improves compatibility.