JavaScript Specifies that event handlers consist of three ways:
(1):D OM0 level event handlers
Such as:
The code is as follows:
var Btn=document.getelementbyid ("Mybtn"); Get a reference to the button
Btn.onclick=function () {
Alert (' clicked ');
alert (this.id); Mybtn
Event handlers that are added in this manner are processed during the bubbling phase of the event flow.
Delete the event handlers specified by the DOM0-level method:
Btn.onclick=null; To delete an event handler
}
(2):D OM2 level event handlers
The DOM2 level event defines two methods for handling the actions of the specified and deleted event handlers: AddEventListener () and RemoveEventListener (). Both methods are included in all DOM nodes, and they all accept 3 parameters: The event name to process, the function that is the event handler, and a Boolean value. The last parameter, if true, indicates that the event handler is called during the capture phase, and if it is Fasle, the event handler is called during the bubbling phase.
Such as:
The code is as follows:
var Btn=document.getelementbyid ("Mybtn");
Btn.addeventlistener ("click", Function () {
alert (this.id);
},false);
The main benefit of using DOM2-level event handlers is that you can add multiple event handlers.
Such as:
The code is 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 added through AddEventListener () can only be removed using RemoveEventListener (), and the parameters passed in when they are removed are the same as the parameters used when they are added. This also means that anonymous functions added through AddEventListener () will not be removed.
Such as:
The code is as follows:
var Btn=document.getelementbyid ("Mybtn");
Btn.addeventlistener ("click", Function () {
alert (this.id);
},false);
Removed from
Btn.removeeventlistener ("click", Function () {//It is useless to write (because the stomach is a completely different function than the first time)
alert (this.id);
},false);
Workaround:
The code is 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 parameter here is false, which is added in the bubbling phase. In most cases, the bubbling phase of event handlers is added to the event stream, which allows for maximum compatibility with various browsers.
[Go]javascript Specify the event handler to include three ways: