A brief talk on several ways of JavaScript event handlers _javascript skills

Source: Internet
Author: User
Tags event listener
An event is an action performed by a user or browser itself. Click,mouseover, for example, are the names of events. The function of the corresponding event is called an event handler (or event listener). There are several ways to specify a handler for an event.
One: HTML event handlers.
Such as:
Copy Code code as follows:

<script type= "Text/javascript" >
Function Show () {
Alert (' Hello world! ');
}
</script>
<input type= "button" value= "click Me" onclick= "show ()"/>

Believe that this is the way we all use more than one, but in the HTML specified event handler has two disadvantages.
(1) First: There is a time difference problem. For this example, let's say the show () function is defined at the bottom of the button, and if the user clicks the button before the page resolves the show () function, an error is raised;
(2) The second disadvantage is that HTML is tightly coupled with JavaScript code. If you want to change the time handler, you need to change two places: HTML code and JavaScript code.
As a result, many developers discard HTML event handlers and instead use JavaScript to specify event handlers.
Two: JavaScript Specify event handlers
JavaScript specifies an event handler that includes three different ways:
(1):D OM0 level event handler
Such as:
Copy Code code as follows:

var Btn=document.getelementbyid ("Mybtn"); Get a reference to this button
Btn.onclick=function () {
Alert (' clicked ');
alert (this.id); Mybtn

Event handlers added in this manner are processed during the bubbling phase of the event stream.
To delete an event handler specified by the DOM0-level method:
Btn.onclick=null; To delete an event handler
}
(2):D OM2 level event handler
The DOM2 level event defines two methods for handling the actions that specify and delete event handlers: AddEventListener () and RemoveEventListener (). Both methods are included in all DOM nodes, and they all accept 3 parameters: the name of the event to be processed, the function as an event handler, and a Boolean value. This last argument, if true, indicates that the event handler is invoked during the capture phase, or if it is fasle, that the event handler is invoked during the bubbling phase.
Such as:
Copy Code code as follows:

var Btn=document.getelementbyid ("Mybtn");
Btn.addeventlistener ("click", Function () {
alert (this.id);
},false);

The primary benefit of using DOM2-level event handlers is that you can add multiple event handlers.
Such as:
Copy Code code as follows:

var Btn=document.getelementbyid ("Mybtn");
Btn.addeventlistener ("click", Function () {
alert (this.id);
},false);
Btn.addeventlistener ("click", Function () {
Alert ("Hello world!");
},false);

There are two event handlers added to the button. The two event handlers are triggered in their order.
The time handlers that are added through AddEventListener () can only be removed by using RemoveEventListener (), and the parameters passed in when they are removed are the same as those used when the addition is added. This also means that anonymous functions added through AddEventListener () will not be removed.
Such as:
Copy Code code as follows:

var Btn=document.getelementbyid ("Mybtn");
Btn.addeventlistener ("click", Function () {
alert (this.id);
},false);
Removed from
Btn.removeeventlistener ("click", Function () {//is not used in this way (because the stomach second is a completely different function than the first time)
alert (this.id);
},false);

Solution:
Copy Code code as follows:

var Btn=document.getelementbyid ("Mybtn");
var hander=function () {
alert (this.id);
};
Btn.addeventlistener ("click", Hander,false);

Btn.removeeventlistener ("click", Hander,false); Effective

Note: Our third argument here is false and is added in the bubbling phase. In most cases, it is the bubbling phase of adding event handlers to the event stream to maximize compatibility with various browsers.
Third: IE event handlers
IE implements two methods similar to the DOM: Attachevent () and DetachEvent (). The two methods accept the same two parameters: the event handler name and the event handler function. Because IE only supports time bubbling, all event handlers added through Attachevent () are added to the packet bubbling phase.
Such as:

Three:
Copy Code code as follows:

var Btn=document.getelementbyid ("Mybtn");
Btn.attachevent ("onclick", function () {
Alert ("clicked");
})

Note: The first parameter of the attachevent () function is "onclick", not "click" in the Dom's AddEventListener ().
The Attachevent () method can also be used to add multiple event handlers to an element.
Such as:
Copy Code code as follows:

var Btn=document.getelementbyid ("Mybtn");
Btn.attachevent ("onclick", function () {
Alert ("clicked");
});
Btn.attachevent ("onclick", function () {
Alert ("Hello world!");
});

Two times attachevent () is called here, and two different event handlers are added for the same button. However, unlike DOM methods, these event handlers are not executed in the order in which they were added, but are triggered in reverse order. Click the button in this example: first See "Hello World", then "clicked".
Events added with attachevent () can be removed by detachevent (), provided the same parameters must be supplied.
Copy Code code as follows:

var Btn=document.getelementbyid ("Mybtn");
var hander=function () {
Alert ("clicked");
}
Btn.detachevent ("onclick", hander}); Removed from

The above three ways for the current main event handler way, then see here you will think that, since different browsers will have different differences, then how to guarantee the Cross-browser event handler?
To handle events in a cross-browser manner, many developers use JavaScript libraries that isolate browser differences, and some developers develop the most appropriate event-handling methods themselves.
This provides a Eventutil object that you can use to handle differences during browsing:
Copy Code code as follows:

var eventutil = {
Addhandler:function (element, type, handler) {//This method takes 3 parameters: the element to manipulate, the event name, and the event handler function
if (Element.addeventlistener) {//check whether the incoming element exists a DOM2-level method
Element.addeventlistener (type, handler, false); If present, this method is used
else if (element.addevent) {//If there is an IE method
Element.attachevent ("On" + type, handler); Use the IE method, note that the event type here must be prefixed with the "on" prefix.
else {//The last one may be using the DOM0 level
Element["on" + type] = hander;
}
},

Removehandler:function (element, type, handler) {//The method is to delete the event handlers that were added before
if (Element.removeeventlistener) {//check whether the incoming element exists a DOM2-level method
Element.removeeventlistener (type, handler, false); If present, this method is used
else if (element.detachevent) {//If there is an IE method
Element.detachevent ("On" + type, handler); Use the IE method, note that the event type here must be prefixed with the "on" prefix.
else {//The last one may be using DOM0 and methods (in modern browsers, the code here should not be executed)
Element["on" + type] = NULL;
}
}
};

You can use the Eventutil object as follows:
Copy Code code as follows:

var btn =document.getelementbyid ("mybtn");
var hander= function () {
Alert ("clicked");
};
Part of the code is omitted here.
Eventutil.addhandler (BTN, "click", hander);
Part of the code is omitted here.
Eventutil.removehandler (BTN, "click", hander); Remove an event handler that was previously added

Visible, it is convenient to add and remove event handlers using AddHandler and RemoveHandler.

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.