English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Traditional method
element.onclick = function(e){ // ... };
1. Advantages of traditional binding
Very simple and stable, ensuring consistent operation across different browsers you use
When handling events, the 'this' keyword refers to the current element, which is very helpful
2. Disadvantages of traditional binding
The traditional method will only run during event bubbling, not during capture and bubbling
An element can only bind one event handler at a time. The new event handler will overwrite the old event handler
The event object parameter (e) is only available in non-IE browsers
W3C method
element.addEventListener('click', function(e){ // ... }, false);
1. W3The advantages of C binding
This method supports both the capture and bubble phases of event handling. The event phase depends on the last parameter setting of addEventListener: false (bubble) or true (capture).
In the event handling function, the this keyword refers to the current element.
The event object can always be captured through the first parameter of the handling function (e)
Multiple events can be bound to the same element as desired, without overwriting previously bound events
2. W3The disadvantages of C binding
IE does not support it. You must use IE's attachEvent function instead.
IE method
element.attachEvent('onclick', function(){ // ... });
1The advantages of .IE method
Multiple events can be bound to the same element as desired, without overwriting previously bound events.
2The disadvantages of .IE method
IE only supports the bubble phase of event capture
The this keyword in the event listener function points to the window object, not the current element (a huge disadvantage of IE)
The event object only exists in the window.event parameter
Events must be named in the form of ontype, such as onclick instead of click
Only available in IE. You must use W in non-IE browsers3C's addEventListener
Dean Edwards' solution (addEvent/removeEvent library)
1The advantages of .addEvent
Works on all browsers, even older browsers with no support
The this keyword can be used in all bound functions, pointing to the current element
Neutralizes all browser-specific functions that prevent browser default behavior and stop event bubbling
The event object is always passed as the first object, regardless of the browser type
2The disadvantages of .addEvent
Only works at the bubble phase (because it deeply uses the traditional way of event binding)
That's all for the introduction of the commonly used methods for JavaScript event binding and their advantages and disadvantages that the editor has brought to you. Hope everyone will support and cheer for the tutorial~