The addHandler method is accused of using the DOM0-level method, DOM2-level method, or IE Method to add events. This method is an object named EventUtil. You can use this object to handle differences between browsers. The addHandler () method accepts three parameters: Elements to be operated, time names, and event handler functions.
The method corresponding to the addHandler () method is removeHandler (), which also accepts the same parameters. This method is accused of removing the previously added event handler ------- no matter how the event handler is added to the element. If other methods are invalid, the DOM0-level method is used by default.
The usage of EventUtil is as follows.
// EventUtil
Var EventUtil = {
AddHandler: 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;
}
},
RemoveHandler: 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;
}
}
}
Var btn1 = document. getElementById ("myBtn1 ");
Var handler = function (){
Alert ("hello handler ");
}
EventUtil. addHandler (btn1, "click", handler );
// EventUtil. removeHandler (btn1, "click", handler );
In the method, check the DOM2 level first. If the DOM2 level method exists, use this method: input the event type, event handler, and the third parameter false (indicating the bubble stage ). If the IE method exists, the second solution is adopted. Note: To run in IE8 or earlier versions, the "on" prefix must be added to the event type. The last one may be the DOM0 method. In this case, we use the parentheses syntax to specify the attribute name as an event handler or set the event to null.