--- title: DOM onevent handlers slug: Web/Guide/Events/Event_handlers translation_of: Web/Guide/Events/Event_handlers ---
Веб-платформа предоставляет несколько способов получения уведомлений о событиях DOM. Два общих подхода - это {{domxref ("EventTarget.addEventListener", " addEventListener ()")}} и конкретные обработчики onevent
. Эта страница посвящена тому, как работают последние.
Обработчики onevent
- это свойства определенных элементов DOM, позволяющие управлять тем, как этот элемент реагирует на события. Элементы могут быть интерактивными (ссылки, кнопки, изображения, формы и т. д.) или неинтерактивными (например, элемент base <body>). События - это такие действия, как:
Обработчик on-event обычно называется с именем события, на которое он реагирует, например onclick
, onkeypress
, onfocus
и т. д.
Вы можете указать обработчик событий on<...> для конкретного события (например, {{event("click")}}) для данного объекта различными способами:
on<eventtype>
:<button onclick="handleClick()">
,document.querySelector("button").onclick = function(event) { … }
.Свойство обработчика событий onevent
служит своего рода заполнителем, которому может быть назначен один обработчик событий. Чтобы разрешить установку нескольких обработчиков для одного и того же события на данном объекте, вы можете вызвать метод {{domxref("EventTarget.addEventListener", " addEventListener ()")}} , который управляет списком обработчиков для данного события на объекте. Затем обработчик можно удалить из объекта, вызвав его функцию {{domxref ("EventTarget.removeEventListener", "removeEventListener()")}} .
Когда происходит событие, которое применяется к элементу, каждый из его обработчиков событий вызывается, чтобы позволить им обрабатывать это событие один за другим. Вам не нужно вызывать их самостоятельно, хотя вы можете сделать это во многих случаях, чтобы легко имитировать происходящее событие. Например, учитывая объект кнопки myButton
, вы можете сделать myButton.onclick(myEventObject)
для прямого вызова обработчика событий. Если обработчик событий не имеет доступа к каким-либо данным из объекта event, вы можете пропустить это событие при вызове функции onclick()
.
This continues until every handler has been called, unless one of the event handlers explicitly halts the processing of the event by calling {{domxref("Event.stopPropagation", "stopPropagation()")}} on the event object itself.
Это продолжается до тех пор, пока не будет вызван каждый обработчик, если только один из обработчиков событий явно не остановит обработку события, вызвав {{domxref("Event.stopPropagation", " stopPropagation ()")}} на самом объекте события.
Event handlers can also be set with properties on non-element objects that generate events, like {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("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 onevent
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 onevent
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.
Given this HTML document:
<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>`);
{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}
For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements instead set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: onblur
, onerror
, onfocus
, onload
, and onscroll
.)
this
binding, and the return valueWhen 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 {{domxref("GlobalEventHandlers.onerror", "onerror")}}.event
, source
, lineno
, colno
, and error
for the {{domxref("GlobalEventHandlers.onerror", "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)
The term 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:
on…
attributes or propertiesSpecification | Status | Comment |
---|---|---|
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}} | {{Spec2('HTML WHATWG')}} | |
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}} | {{Spec2('HTML5 W3C')}} |
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.