By specifying an event handler, you can listen for an event and respond to it for some kind of interaction purpose. So what are the ways to specify event handlers ?
For example, the following code is available:
<id= "btn" type= "button" value= "click me" />
Requires that you specify a click event handler for the button, which outputs the appropriate information when the button is clicked.
1.HTML Event handlers
Each event supported by an element can be specified using an HTML attribute with the same name as the corresponding event handler . The value of the attribute can be a JS code that can be executed.
<ID= "btn" Value= "click me" onclick/>
You can also invoke scripts defined elsewhere on the page.
<script type= "Text/javascript">
function ShowMessage () {
Alert ("clicked");
} </script>
<inputID= "BTN"value= "click me"onclick= "ShowMessage ()" />
ShowMessage () This function can be defined in the above way, or it can be included in an external file. Code in an event handler has access to any code in the global scope when it executes.
Disadvantages:
- Time difference: The condition does not exist because the event handler needs to be triggered. The workaround is to encapsulate the HTML event handler in a Try-catch block so that the error does not surface.
<type= "button" value= "click me" onclick= " Try{showmessage ();} catch (ex) {} "/>
- Scope chain: Due to the fact that the JavaScript engine of different browsers follows an identifier parsing rule for bare-travel differences, the scope chain of the extended event handler may cause different results.
- HTML is tightly coupled with JavaScript code: If you want to replace an event handler, you need to modify two places at the same time.
2.dom0 Level Event handlers
The traditional way to specify handlers through JavaScript is to assign a function to an event handler property. Each element, including document and window, has its own event handler properties, which are usually all lowercase, such as onclick.
var btn = document.getElementById ("btn"); // Specifying event Handlers function () { alert ("Clicked");}; // If you want to cancel an event handler, simply set the event handler property to null null;
The event handler specified in this manner is considered to be an element's method, so its scope is the scope of the element. that is, the this in the program refers to the current element. Such as:
btn.onclick=function() { alert (this. id); btn}
Another event handler added in this way is processed during the bubbling phase of the event flow .
3.dom2 Level Event handlers
The "DOM2 level event" defines two methods for handling the actions of the specified and deleted event handlers:AddEventListener () and RemoveEventListener (). All DOM nodes contain two methods, and they all accept three parameters: the event name to be processed, the function of the event handler, and a boolean value . Where a Boolean value of TRUE indicates that the event handler is called during the capture phase, and False indicates that the event handler is called during the bubbling phase.
// Specifies the event handler Btn.addeventlistener ( "Click", Fucntion () {alert ("clicked"),},false // Cancel event handler Btn.removeeventlistener ("click", () {alert ("clicked"),},false ); // invalid // The specified and canceled parameters must be identical to be valid. The anonymous function is two different functions, so invalid // So in order to be able to cancel, The best function takes a named function
var function () { alert ("clicked");}; // Add Event handler btn.addeventlistener ("Click", Handler,false); // cancels the event handler btn.removeeventlistener ("Click", Handler,false); // effective
Scopes and DOM0-level events Specify the scope of the event handler, which is also the scope of the element . However , unlike DOM0, DOM2 can specify multiple event handlers .
The order in which the event handlers are triggered is in the order in which the event handlers are added.
Browsers that support DOM2-level event handlers are ie9+, Firefox, Safari, Chrome, and opera.
4.IE Event handlers
IE implements two methods similar to DOM:attachevent () and DetachEvent (). accepts two parameters: an event handler name and an event handler function . Ie8-only supports event bubbling, so event handlers added through Attachevent () are added to the event bubbling phase.
// Add Event handler btn.attachevent ("onclick", handler); // cancels the event handler btn.detachevent ("onclick", handler); // The cancellation parameter must be exactly the same as the add, so the event handler function (like the analysis in the DOM2-level event) is not an anonymous function.
The biggest difference between the IE event handler and the DOM event handler is that the scope of the DOM0/2 event handler is the element scope, and the IE event handler is the global scope, that is, this equals widow.
IE can also specify multiple event handlers, and I run the related code discovery: The trigger sequence is the same as the order of addition (IE9), while the JavaScript Advanced program design says that the triggering sequence should be the opposite of the order of addition. In the end is not clear.
Browsers that support IE event handlers have IE and opera.
5. Cross-browser event handlers
//cross-browser event handlers can be implemented with the proper ability to detect //to ensure that the code of the event runs consistently under most browsers, just focus on the bubbling phase //The first method to be created is AddHandler (), where the responsibility is to use DOM0-level methods, DOM2-level methods, respectively , as appropriate //or IE method to add events. This method belongs to an object named Eventutil. //accepts three parameters: the element to manipulate, the event name, and the event handler function //RemoveHandler () also accepts the same parameters. The responsibility is to remove the previously added event handler-no matter how the event is added to the element, and if the other method is not valid, the DOM0-level method is used by default varEventutil ={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; } } }; varHandler =function() {alert ("Clicked"); }; //SpecifyEventutil.addhandler (BTN, "click", Handler); //removing event handlersEventutil.removehandler (BTN, "click", Handler); //Note that the above AddHandler () and RemoveHandler () do not take into account all browser issues, such as the scope problem in IE //However, it is sufficient to use them to add and remove event handlers. Also note that the DOM0 level supports an event handler for each event. //Fortunately, browsers that only support DOM0 levels are not that many.
Several ways to specify event handlers