AddEventListener () and RemoveEventListener () are used to process the specified and delete event handler actions. Both methods are included in all DOM nodes, and they all accept 3 parameters: the name of the event to be processed, the function that is the event handler, and a Boolean value. Most of this Boolean parameter is true, which means that the event handler is called during the capture phase, or false to indicate that the event handler is called during the bubbling phase.
To add an event handler for the Click event on the button, you can use the following code:
var btn = document.getElementById ("mybtn"); Btn.addeventlistener (function () { Alert (thisfalse);
The main benefit of adding event handlers using the DOM2-level method is that you can add multiple event handlers. Take a look at the following example:
var btn = document.getElementById ("mybtn"); Btn.addeventlistener (function () { Alert (thisfalse); Btn.addeventlistener (function () { Alert ("Hello World"false);
Event handlers 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 adding handlers. This also means that anonymous functions added through AddEventListener () cannot be removed, as shown in the following example:
var btn = document.getElementById ("mybtn"); Btn.addeventlistener (function () { Alert (thisfalse); Btn.removeeventlistener (function () { // Invalid! alert(thisfalse);
In this example, I use AddEventListener () to add an event handler. Although calling RemoveEventListener (0) is seemingly using the same parameters, the second argument is actually a completely different function from the one passed in AddEventListener (). The event handler function in the incoming RemoveEventListener () must be the same as in the incoming AddEventListener (), as shown in the following example:
var btn = document.getElementById ("mybtn"); var function () { alert (this. id); }; Btn.addeventlistener (false); Btn.removeeventlistener (false) ; // Effective!
This example of rewriting is no problem because the same function is used in AddEventListener () and RemoveEventListener ().
In most cases, the event handlers are added to the bubbling phase of the event stream, which maximizes compatibility with various browsers. It is best to add an event handler to the capture phase only when it needs to be intercepted before it is time to reach the target. If not specifically required, we do not recommend registering an event handler during the event capture phase.
JavaScript--AddEventListener () and RemoveEventListener