EventUtil addHandler removeHandler

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.