DOM Event handlers: DOM0-level event handlers, DOM2-level event handlers
DOM0-level Event handlers:
For example: var btn = document.getElementById (' mybtn ');
Btn.onclick = function () {
Event handling Logic
}
Through Btn.onclick =null; You can delete an event handler
DOM2-level Event handlers:
For example: var btn = document.getElementById (' mybtn ');
Btn.addeventlistener (' click ', function () {
Event handling Logic
},false);
Description
AddEventListener: Add event handling, receive three parameters: 1, Event type name 2, event handler 3, Boolean value--true: Indicates that event handlers are called during the capture phase, false: Indicates that event handling is called during the bubbling phase, Use AddEventListener () to add events of the same type to multiple events, which are executed in order.
RemoveEventListener: Remove the event handler, the parameter is the same as the parameter used by the add handler, one thing to note is that the anonymous function cannot be removed, so the function name that adds the event handler function and removes the event handler is the same
For example: var btn = document.getElementById (' mybtn ');
var hander = function () {
alert (this.id);
}
Btn.addeventlistener (' Click ', hander, false);
Btn.removeeventlistener (' click ', Hander,false)
IE8 and earlier/opera browser event handlers:
Implemented by Attachevent () and DetachEvent () two methods. Two methods receive the same parameters: event handler name and function of event handler
Note: The main difference between using attachevent () and using the ODM0-level method is the scope of the event handler. In the case where the ODM0-level method is used, the event handler runs within the scope of the element to which it belongs, and in the case of the Attachevent () method, the event handler runs in the global scope, so this is equal to the window
For example: Var btn =document.getelementbyid (' mybtn ');
var hander = function () {
Event handling Logic
}
Btn.attachevent (' onclick ', hander);
Btn.detachevent (' onclick ', hander);
Event handlers that can cross-browser
To ensure that the code that handles events runs consistently under most browsers, just focus on the bubbling phase. The following processing method, receive three parameters (the element to be manipulated, the event name, the event handler function)
var eventutil = {
Addhandle:function (element, type, handler) {
if (Element.addeventlistener) {
Element.addeventlistener (Type,handler,false);
}else if (element.attachevent) {
Element.attachevent ("on" +type,handler);
}else{
element["on" +type] = handler;
}
},
Removehandle:function (Element,type,handler) {
if (Element.removeeventlistener) {
Element.removeeventlistener (Type,handler,false);
}else if (element.detachevent) {
Element.detachevent ("on" +type,handler);
}else{
element["on" +type] = null;
}
}
}
DOM Event handlers