I recently read the book "javascript advanced program" and write my own experiences with caution. I hope you can get some guidance and discussion from the ox.
Today's question is: javascript event processing functions. We know that interaction between JavaScript and HTML is implemented through events. Events are actions performed by users or browsers, for example, click, mounseover, load ......, The function that responds to an event is called an event processing function (or an event listener ).
- Event handler in HTML code:
<input type="button" value="click me" onclick="alert('click me')" />
Here, we directly inline the event handler into the HTML code, but this is extremely unfriendly for us to read the code. Below we separate the event handler, as shown below:
function showMessage() {alert("click me");}
Then we call the following in the HTML code:
<input type="button" value="click me" onclick="showMessage()" />
Specifying event processing functions in HTML has two disadvantages:
1. Time DifferenceIn the preceding example, assume that the showmessage () function is defined at the bottom of the page. If you click the button before parsing the showmessage () function, an error is thrown. For this reason, many HTML event processing functions are closed in the try-Catch Block, so that the error will not be exposed, as shown below:
<input type="button" value="click me" onclick="try {showMessage()} catch(e) {}" />
2. Close coupling between HTML code and JavaScript codeIf you want to update the event processing function, you need to update the two locations. Because of these two problems, we generally seldom use this event processing method in actual work.
- Dom0-level event handler:
var btn = document.getElementById("myBtn");btn.onclick = function() {alert("clicked!");}
Assign a function to the attribute of an event handler. Since this method is currently supported by all browsers, it is easy to use and cross-browser! The event handler specified by the dom0-level method is considered an element method. At this time, the event runs in the element scope, that is, this in the program references the current element.
You can also delete the event handler specified by the dom0-level method, as shown below:
btn.onclick = null;
- Dom2-level event handler:
Dom2 events define two methods: addeventlistener () and removeeventlistener ()
To add an event handler for the click button, use the following code:
var btn = document.getElementById("myBtn");btn.addEventListener("click", function() {alert(this.id);}, false);
Because the third parameter is false, the event is triggered in the bubble stage. The advantage of using a dom2-level event handler is that multiple event handlers can be added.
We can also remove the Event Handler through removeeventlistener (), as shown below:
var btn = document.getElementById("myBtn");btn.removeEventListener("click", function() {alert(this.id);}, false);
IE implements two methods similar to Dom, attachevent and deatachevent (), as shown in the following code:
var btn = document.getElementById("myBtn");btn.attachEvent("click", function() {alert(this.id);});var btn = document.getElementById("myBtn");btn.detachEvent("click", function() {alert(this.id);});
- Cross-browser Event Handlers:
Because the dom2-level event handler is different from the event handler in IE, we may use the capability to detect the unified event handler, as shown in the following code:
var eventUtil = {addListener: function(element, type, hander) {if (element.addEventListener) {element.addEventListener(type, hander, false);} else if (element.attachEvent) {element.attachEvent('on' + type, hander);} else {element['on' + type] = hander;}},removeListener: function(element, type, hander) {if (element.removeEventListener) {element.removeEventListener(type, hander, false);} else if (element.deattachEvent) {element.detachEvent(type, hander);} else {element['on' + type] = null;}},};
A dom-compatible browser will have an event object passed into the event handler. No matter what method is used in the specified event handler, the event object will be passed in, the attributes and methods of common event objects include:
1. currenttarget: the element whose event handler is currently processing the event;
2. Target: The Event target;
3. preventdefault (): cancels the default event behavior;
4. stoppropagation (): cancels the event to further capture and bubble.
Like the event object in Dom, the event object in IE also has the above attributes or methods, but the implementation is somewhat different. The following is the correspondence between them:
1. srcelement <=> target;
2. returnvalue = false <=> preventdefault ();
3. cancelbubble = true <=> stoppropagation ();
- Cross-browser event objects:
Because the event objects in Dom are different from those in IE, we can also use the capability detection method to unify the attributes and Methods Commonly Used in event objects (eventutil. JS ):
var eventUtil = {addListener: function(element, type, hander) {if (element.addEventListener) {element.addEventListener(type, hander, false);} else if (element.attachEvent) {element.attachEvent('on' + type, hander);} else {element['on' + type] = hander;}},getEvent: function(event) {return event || window.event;//return event ? event : window.event;},getTarget: function(event) {return event.target || event.srcElement;},preventDefault: function(event) {if (event.preventDefault) {event.preventDefault();} else {event.returnValue = false;}},removeListener: function(element, type, hander) {if (element.removeEventListener) {element.removeEventListener(type, hander, false);} else if (element.deattachEvent) {element.detachEvent(type, hander);} else {element['on' + type] = null;}},stopPropagation: function(event) {if (event.stopPropagation) {event.stopPropagation();} else {event.cancelBubble = true;}}};
Finally, we can use a simple example to demonstrate how to use a custom eventutil object. The complete sample code is as follows: