Javascript event processing and javascript events

Source: Internet
Author: User

Javascript event processing and javascript events

[Written above] I have been reading the basis of js recently. After all, although jquery is easy to use, it is always written by others. It is better to understand the implementation principle than to use APIs. After the js foundation is consolidated, you must read the jquery source code.

Event stream

The event stream describes the sequence of events received from the page. Js has two types of event streams: Bubble stream and capture stream. The names of the two streams are very good. On an html tree composed of nodes, a bubble stream is the first to receive events from the most specific elements at the beginning, then spread to the least specific node step by step, for example, in the following document:

<!doctype html>

When you click a div, the event first responds to the div, then uploads it to the body element, then uploads it to the html element, and finally uploads it to the document Object.
The opposite is true for the captured stream. The first response is the document object, and then goes down along the dom tree to html, to the body, and finally to the actual target, that is, the div.
The browser of the old version does not support capturing streams. The bubble stream is also very consistent with our understanding of event propagation. Therefore, we use the bubble stream more.

Several Methods for event processing

Many events are defined in js event processing. Event names refer to specific actions, such as click, load, and mouseover. WhileResponse to an eventA function is called an event handler. The name of an event handler starts with on. Therefore, the event handler for a click event is onclick, and the event handler for a load event is onload.

Tag binding

By setting tag attributes, you can easily bind events to nodes, such:

<Input type = "button" value = "button" onclick = "alert ('button click')">

You can also call scripts defined elsewhere:

<Script> function showMessage () {alert ("press the button") ;}</script>... <input type = "button" value = "button" onclick = "showMessage ()">

There are two special points for direct binding,One is to create a function that encapsulates element attributes.In this function, there is a local variable event, that is, the event object:

<! -- Output 'click' --> <input type = "button" value = "button" onclick = "showMessage (event. type)">

When an event is generated, the event object is automatically transmitted to the showMessage function. With this object, we can access many attributes of the event object. In addition, in the event handler, this refers to the target element of the event, such

<! -- Output 'button '--> <input type = "button" value = "button" onclick = "showMessage (this. value)">

When the current element is a form element, the scope also contains the entry of the form ElementIn other words, other form elements can be accessed in the event handler, such

<Form> <input type = "text" name = "username"/> <input type = "button" value = "button" onclick = "alert (username. value) "> </form>

In this way, the values in username can be output directly.

However, although the event processing added in this way is intuitive and convenient, there are many disadvantages:
(1) because the page loading sequence is from top to bottom, if the bound script is written below the html, the script may not be executed when the user clicks the element, causing the user to not respond for half a day, such:

<Input type = "button" value = "button" onclick = "showMessage ()"> ...... // many contents... <script> function showMessage (){//...} </script>

(2) Close Combination of html and js code, such as the showMessage method. If many elements in the Interface Bind this method in this way, if you want to change the name of this function at one time, you need to change many places at the same time, which is quite troublesome.

DOM0-level processing program

The second method is to bind an event to the element in js, get the element in js, and then specify the event for it:

var btn = document.getElementById("button");btn.onclick = function(){    alert(this.id);}

The program specified by the DOM0-level method is considered an element method. After the code is executed, the button id is displayed when the element is clicked, you can use this to obtain all attributes and methods of this element.
To delete the event handler specified by the DOM0-level method, you only need to set this attribute value to null:

btn.onclick = null;

Note that you cannot add duplicate events to elements in this way. Only the last one is valid when assigning values to onclick multiple times,For example

btn.onclick = function(){    alert("first");}btn.onclick = function(){    alert("second");}

When the button is clicked, only second is output.

DOM2-level processing program

IE9, Firefox, chrome, safari, and opera Support DOM2-level event handlers
"DOM2-level events" define two methods for specifying and deleting the operations of Event Handlers: addEventListener () and removeEventListener (). All DOM nodes have this method and receive three parameters: event name, event processing function, and a Boolean value. This Boolean value indicates whether to use capture or bubble. true indicates processing in the capture phase. false indicates processing in the bubble phase. If this parameter is left blank, the default value is false.

var btn = document.getElementById("button");btn.addEventListener("click", function(){    //...}, false);

Unlike DOM0-level event processing, event processing bound using this method can be added multiple times, such

var btn = document.getElementById("button");btn.addEventListener("click", function(){    alert("first");}, false);btn.addEventListener("click", function(){    alert(this.id);}, false);

In addition, this also refers to the target element in the function. After you click the button, first is output, and then the btn id is output.
Events added through addEventListener can only be removed through removeEventListener, and the parameters must be the same (the three parameters are the same). This means that events bound with anonymous functions cannot be removed, it is best to define the event processing function separately.

Btn. addEventListener ("click", function () {alert ("first") ;}, false); btn. removeEventListener ("click", function () {alert ("first") ;}, false); // No effect btn. addEventListener ("click", showMessage, false); btn. removeEventListener ("click", showMessage, false); // removed successfully
IE event handler

Internet Explorer implements two methods that are similar to DOM2-level event processing: attachEvent and detachEvent (). The two methods receive two parameters: the name of the event handler and the event handler. Because IE8 and earlier versions only support event bubbling, Event Handlers added in this way will be added in the event bubbling phase.

Var btn = document. getElementById ("button"); btn. attachEvent ("onclick", function () {// note that onclick alert ("first ");});

There are two differences between IE event processing and other methods,First, the event handler of IE runs in the global environment.
This means that using this in it will be equal to window.

var btn = document.getElementById("button");btn.attachEvent("onclick", function(){    alert(this === window);  //true});

Second, the event handler function added multiple times is executed in the reverse order of addition,For example

var btn = document.getElementById("button");btn.attachEvent("onclick", function(){    alert("first");});btn.attachEvent("onclick", function(){    alert("second");});

When the button is pressed, second is output first, and then first is output.
The method for removing an event is similar to that for DOM2. You can call detachEvent and pass it as the same parameter.

Compile a cross-browser event handler

As mentioned above, there are still some differences between IE and other browsers in processing events. You can write an EventUtil object to encapsulate add events and remove events.
The implementation method is to determine whether the DOM2-level processing is supported first. If the IE method is not supported, the DOM0-level method is not supported at the end.

Var EventUtil = {// Add event addHandler: function (element, type, handler) {if (element. addEventListener) {// supports DOM2-level elements. addEventListener (type, element, handler);} else if (element. attachEvent) {// handle IE events. Pay attention to the on prefix element. attachEvent ("on" + type, handler);} else {// DOM0 level element ["on" + type] = handler ;}}, // remove event removeHandler: function () {if (element. removeEventListener) {// supports DOM2-level elements. removeEventListener (type, element, handler);} else if (element. detachEvent) {// IE event processing. Note that the on prefix is element. detachEvent ("on" + type, handler);} else {// DOM0 level element ["on" + type] = null ;}}}

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.