JavaScript Event Processing parsing

Source: Internet
Author: User
Tags event listener

First, what is an event! (interpretation by the consortium)

Events are behaviors that can be detected by JavaScript.

JavaScript gives us the ability to create dynamic pages. Events are behaviors that can be detected by JavaScript.

Each element in a Web page can produce certain events that can trigger JavaScript functions. For example, we can trigger a function by generating an OnClick event when the user taps a button. The event is defined in the HTML page.

Ii. level of events

In the work we write JS code when there will be two kinds of writing JS habits, as follows:

The first way of writing var btn3 = document.getElementById ("Btn3"); Btn3.onclick = function () {/* here executes the corresponding code */};//This writing method is the way of writing DOM0-level events/ /The second way of writing var btn3 = document.getElementById ("Btn3"); Btn3.addeventlistener (' Click ', function () {/* * here Execute the corresponding code */},false) ;//This is the Dom2 level event handling method

Two handler functions for adding and deleting events are defined in the Dom2 level event handler:

AddEventListener (' event ', function, whether bubbling flag);

RemoveEventListener (' event ', function, whether bubbling flag);

Parameter description: ' event ', such as clicking Event ' click ', ' function ' refers to the action that needs to be processed after the event occurs, can call the function name directly, or you can write code here, ' Bubble flag ', set false bubble, set true to capture.

The parameter values for adding and deleting events are exactly the same.

Note: Functions added with AddEventListener can only be deleted by RemoveEventListener, setting null does not work, and the parameters of the delete event should be exactly the same as the parameters of the Add event.

First Kind
var btn3 = document.getElementById ("Btn3"), Btn3.addeventlistener (' click ', Function () { alert (' button ');},false);
Btn3.removeeventlistener (' click ', function () {Alert (' button ');},false);
The second Kind
Btn3.addeventlistener (' click ', Showmess,false);
Btn3.removeeventlistener (' click ', Showmess,false);
function showmess () {
Alert (' button ');
}

Dom2 level event handler is not supported under IE, IE has its own DOM2 level event handler function:

As follows:

Attachevent (' onclick ', showmess);//ie Add event below
DetachEvent (' onclick ', showmess);//ie Delete Event

The parameters of the two event handlers under IE are exactly the same!

There is no event bubbling logo under IE, because IE defaults to handling events in the form of bubbling!

Iii. bubbling and capturing of events

1. Definition of Event Stream

The DOM event standard defines two kinds of event streams, which are significantly different and may have a considerable impact on your application. The two streams of events are capture and bubbling, respectively. Like many web technologies, Netscape and Microsoft have implemented them differently before they become standards. Netscape chose to implement the capture event stream, and Microsoft implemented the bubbling event stream. Fortunately, the consortium uses both approaches, and most new browsers follow these two streams of events.

2. What is event bubbling stream

When an event is triggered on a DOM element, such as when a user clicks on the client's name node, the event will bubble through the entire DOM node hierarchy as the parent node inherits from the node, until it encounters a node attached to the event type processor, which is the OnClick event at this time. The bubbling of events can be terminated at any time during the bubbling process, which can be done by invoking the Stoppropagation () method on the event object on the Internet Explorer can be set by setting the event object's Cancelbubble property to True. If you do not stop the propagation of an event, the event continues to bubble through the DOM until it reaches the document root.

3. What is an event capture stream

The processing of the event begins at the root of the DOM hierarchy, not from the target element that triggers the event, and the event is passed down from all ancestor elements of the target element. In this process, events are captured from the document root to the elements of each inheritance derivation between the event target elements, and if the event listener is registered with the Usecapture property set to True, then they can be assigned to any element of the period to handle the event; The event is then passed to the next element on the path of the derived element until the target element. When the event reaches the target element, it then bubbles through the DOM node.

4, different browser processing under the bubble and capture in non-IE browser, blocking event bubbling is through the function stoppropagation (); In IE, it is by setting the variable cancelbubble = True to prevent the event from bubbling, which is a variable specific to IE.

Use the following:

function Stoppropagation (event) {   if (event.stoppropagation)      {        event.stoppropagation ();//Non IE      }    Else      {        event.cancelbubble = true;//ie      }   }

In general, the handling of events is handled by bubbling, so the handling of event captures is only available in special cases!

Iv. default behavior of events

The default behavior of an event is the behavior that the tag gives at design time, such as the default behavior of a tag is the jump page, and the default behavior of the Submit button is to submit the form! Sometimes we do not want tags to perform their default behavior in a particular environment, and this will use the program to block the default behavior of the event! Of course, the general method of blocking the default behavior of an event is to set return false, but this method is dangerous and may cause all subsequent programs to fail, so in general, we use the default method of the browser to block the default behavior of the event.

The default behavior for blocking events under non-IE is through the function preventdefault ();

Under IE, it is prevented by setting the variable returnvalue = false;

Use the following:

function Preventdefault (event) {  if (Event.preventdefault)   {     event.preventdefault ();//Non ie   }    else   {     event.returnvalue = false;//ie   }
}

V. Event encapsulation

var eventmy={//Add Event Adde:function (Element,type,handler) {if (element.addeventl               Istener) {Element.addeventlistener (type,handler,false);               }else if (element.attachevent) {element.attachevent (' on ' +type,handler); }else{
//In JS the brackets are equivalent to "." element[' on ' +type]=handler; }},//delete event Removee:function (Element,type,handler) {if (Element.removeev Entlistener) {Element.removeeventlistener (type,handler,false); }else if (element.detachevent) {element.detachevent (' on ' +type,handler); }else{element[' on ' +type]=null; }}, Gete:function (event) {//Get Events Object
 /*
Event Enent can be obtained directly from browsers other than IE and IE8,
and before the IE8 browser to get through the window.event
*/return event?event:window.event; }, Getetype:function (event) {return event.type;//gets the type of event, such as ' click '}, Getetarget:funct Ion (event) {
//Get event target in non-IE with e.target, under IE with e.srcelement return event.target | | event.srcelement; }, Preventdefault:function (event) {if (Event.preventdefault) {event.preventdefault ();//Block things Default behavior of the piece (non IE)}else{event.returnvalue=false;//block event default behavior (IE)}, STOPPR Opagation:function (Event) {if (event.stoppropagation) {
//Block event bubbling (non IE) event.stoppropagation (); }else{
//Block event bubbling (IE) event.cancelbubble=true; } } }

Here's how to use it:

Window.onload=function () {  var Go=document.getelementbyid (' Go '),      box=document.getelementbyid (' box ');  Eventmy.adde (box, ' click ', Function () {      alert (' one ');  });  Eventmy.adde (Go, ' click ', Function (e) {      E=e | | | window.event;//HERE for convenience do not call the encapsulated code directly to get      alert ( Eventmy.getetarget (E). nodeName);//e.target.nodename Gets the node name of the event vector for the event      Eventmy.preventdefault (e);      Eventmy.stoppropagation (e);  });

JavaScript Event Processing parsing

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.