Learn the basics of JavaScript in one step (8): A Story in detail

Source: Internet
Author: User

Finally learned the event, do not know why hear the "incident" there is a strange excitement. It may be that the previous knowledge point is too dull, said the incident felt suddenly tall. Today we are going to do a good analysis of this big thing.

It can be said that if there is no event, our page can only be read. With events, we can interact with the keyboard or mouse and the page, giving different responses through our different action pages. Well, let's start with our analysis today.

DOM0 Level Event Handling mode

What is the DOM0 level?

In fact, there is no DOM0 level, called more people have a DOM0 class.

In October 1998, DOM1-level specification became the recommended standard of the World Wide Web, before the implementation of our custom is called DOM0 level, in fact, this is not the standard.

<input type= "button" value= "but" id= "but"/><script type= "Text/javascript" >     document.getElementById (function  () {        alert ("click button 1");    }    document.getElementById (function  () {        alert ("click button 2");     </script>

The above code, we found that when clicked button, only pop up "click Button 2". The previous defined method is overwritten. This overrides the previous event definition in the way we call the DOM0 level event.

If we use jquery to add events:

<script src= ". /scripts/jquery-1.8.2.js "></script><input type=" button "value=" but "id=" but "/><script type=" text /javascript ">    $ (" #but "). Click (function  () {        alert (" click button 1 ");    });    $ ("#but"). Click (function  () {        alert ("click button 2");    });

We'll find out in turn "click Button 1", "click Button 2", how is this done? Why not overwrite the last definition, I guess it should be using the DOM2 level event mechanism. ( I have not read the source of jquery, but I do not understand it at the moment ).

DOM2 Level Event Handling mode
<input type= "button" value= "but" id= "but"/><script type= "Text/javascript" >           document.getElementById (function  () {        alert ("click button 1");    });    document.getElementById (function  () {        alert ("click button 2");    });         </script>

The way to add this through the AddEventListener of an element object is a level 2 event. It is important to note that unlike level 0 events, event names cannot be preceded with "on". Clicking the button pops up the same way as the previous jquery Add.

One might ask, how there is no DOM1 level event. What I can say is no, no, no why. There is no need to extend the event definition mechanism when determining DOM1-level standards, and events at the DOM0 level are sufficient.

We just added the method through Level 2 events, so if we want to remove one of them. If this is the anonymous method above, I can tell you clearly that there is no way to remove it. Let's say we can remove the Add method:

 <input type= "button" value= "but" id= "but"/><script type= "Text/javascript" > document.getElementById ( "but"). AddEventListener ("click", Fun1); //  document.getElementById ("but") to the Click event. AddEventListener ("click", FUN2); //     function      Fun1 () {Alert ( clicked button 1 " function   fun2 () {alert ( "clicked on    Button 2 "); } document.getElementById ( "but"). RemoveEventListener ("click", Fun1); //  Remove method fun1  </script> for the click event; 

This is done by removing the RemoveEventListener method.

The above is only the standard implementation of the DOM2 level, of course, except IE, this freak must be a dung stick. Under IE, there is an implementation function with the same effect:

<input type= "button" value= "but" id= "but"/><script type= "Text/javascript" >document.getElementById ("but"). Attachevent ("onclick", fun1,false);//add a method to the Click event Fun1document.getElementById ("but"). Attachevent ("onclick", fun2,false);//add a method to the Click event fun2    functionfun1 () {alert ("Click on button 1"); }    functionfun2 () {alert ("Click on button 2"); } document.getElementById ("but"). DetachEvent ("onclick", fun1);//to remove a method from the Click event fun1

Note: attachevent () and detachevent () replace AddEventListener () and RemoveEventListener (), and the first parameter is "on" preceded by the event name.

DOM3 level Events

Some people may find it strange, where the DOM3 level event AH. In fact, the DOM0-level and DOM2-level events described above are the way events are handled, and the DOM3-level event here is said to be a new event in the DOM3 level.

As for the DOM1-level event, I really haven't heard of it.

DOM3-level events are redefined on the basis of DOM2 events, or new events are added. such as mouse events:

DOM2, click, MouseDown, MouseMove, Mouseout, MouseOver, MouseUp
In the DOM3 class there are, click, DblClick, MouseDown, MouseEnter, MouseLeave, MouseMove, Mouseout, MouseOver, MouseUp

(where DblClick, MouseEnter, MouseLeave are new in DOM3)
DOM3-level event implementations can be implemented in DOM0 and DOM2 levels, except for new write event types. This is not an exhaustive list.

Event bubbling

What is event bubbling? Let's look at an example first.

 <div onclick= "Divfun ()," style= "border:1px dashed red;padding:50px" > <span onclick= "Spanfun ();" Style= " border:1px dashed #00ff21; padding:30px; "> <input type=" button "value=" but "onclick=" Butfun (); "style=" border:1px dashed #0094ff "/> </span ></div><script type= "Text/javascript" > function   Butfun () {Alert ( button was clicked " function   Spanfun () {alert ( s    Pan was clicked ");  function   Divfun () {alert ( "Di    V was clicked "); }  </script> 

A div packs a span, and a button is wrapped in span. When we click the button, we trigger the button event, then trigger the span click event and then trigger the DIV's Click event. This is the event bubbling. ( using DOM0-level events is the default event bubbling mode )

Event capture

What is event capture? is actually the reverse of event bubbling.

So how do we achieve this effect? We can pass the DOM2 level event. Above, we have simply explained how the DOM2-level event is implemented.

Add and remove functions to events through AddEventListener and RemoveEventListener. When we talk about AddEventListener, if you look back, we only give two parameters, the first is the event name, the second is the method to be added, and in fact there is a third argument a Boolean value to represent the event flow direction (True for the event capture direction, False is the event bubbling direction ). Then we can achieve the effect of event capture through DOM2 level events, such as:

<div id= "mydiv" style= "border:1px dashed red;padding:50px" > <span id= "mysapn" style= "border:1px dashed #00ff2 1; padding:30px; "> <input id=" mybut "type=" button "value=" but "style=" border:1px dashed #0094ff "/> </span></ Div><script type= "Text/javascript" >document.getElementById ("Mydiv"). AddEventListener ("Click", Divfun,true); document.getElementById ("MYSAPN"). AddEventListener ("Click", Spanfun,true); document.getElementById ("Mybut"). AddEventListener ("Click", Butfun,true); functionButfun () {alert ("button is clicked."); }    functionSpanfun () {alert ("Span has been clicked"); }    functionDivfun () {alert ("Div was clicked."); }</script>

Similarly, we can also through the DOM2 level event bubble event, on the above code just need to change the third parameter of AddEventListener to False can be, interested students can try their own.

Then ie this stir-doo stick again, I will not implement the event capture what you can do to me. The equivalent implementation of the attachevent in IE does not give the third parameter, so in order to be compatible, we usually only use event bubbling (ie only supports event bubbling).

Use of event bubbling
    • Cancel Event Bubbling

By the above, we know that as soon as the button is clicked, the click event in the upper element of the button will be triggered. Then we think that if I just want to click on an element of the TM to trigger, do not want to let it go up to do, see below:

<div id= "mydiv" style= "border:1px dashed red;padding:50px" > <span id= "mysapn" style= "border:1px dashed #00ff2 1; padding:30px; "> <input id=" mybut "type=" button "value=" but "style=" border:1px dashed #0094ff "/> </span></ Div><script type= "Text/javascript" >//The third argument is false, then the event bubbles.document.getElementById ("Mydiv"). AddEventListener ("Click", Divfun,false); document.getElementById ("MYSAPN"). AddEventListener ("Click", Spanfun,false); document.getElementById ("Mybut"). AddEventListener ("Click", Butfun,false); functionButfun (Event) {event.stoppropagation ();//Cancel event Bubbling when the button is clickedAlert ("The button is clicked"); }    functionSpanfun () {//There is no cancel event bubbling, so clicking on span will continue to bubble to DivAlert ("Span is clicked"); }    functionDivfun () {alert ("Div was clicked."); }</script>

If you look carefully, then you will find. When you click on the button, it doesn't bubble, and when you click Span, it's bubbling. That's because we've added event.stoppropagation ()// Cancel Bubbles to the method of the button event in our code.

    • Event delegate

Now that we can do this, we can add a cancellation bubble to each of the event methods, then all the elements will only implement their own event-corresponding method. We found this event bubbling instead of getting in trouble, and a good element corresponds to an event. Why bubble up, and manually cancel bubbling. Since there is this thing, it always has its function. As we see above we define the event method, we take each element and then define the method for each element. So can we define a method of event bubbling to implement it, first look at the following code:

<div id= "mydiv" style= "border:1px dashed red;padding:50px" > <span id= "mysapn" style= "border:1px dashed #00ff2 1; padding:30px; "> <input id=" mybut "type=" button "value=" but "style=" border:1px dashed #0094ff "/> </span></ Div><script type= "Text/javascript" >//The third argument is false, then the event bubbles.document.getElementById ("Mydiv"). AddEventListener ("Click", Divfun,false); functionDivfun (event) {varTargetid =event.target.idif(Targetid = = "Mybut") {alert ("button is clicked."); } Else if(Targetid = = "MYSAPN") {alert ("Span has been clicked"); } Else if(Targetid = = "Mydiv") {alert ("Div was clicked."); }     }</script>

Looking closely at you, you will find that we click on each element to trigger the corresponding message. This is the same effect that we add to each element above and then cancel the bubbling. Then we'll analyze the implementation code, and we'll find that it uses bubbling instead.

event.target//returns the target node of the event (the node that triggered the event) var targetid = event.target.id // returns the ID of the target node for the event (the ID of the node that triggered the event)

Because we add the method of events to the outermost div, we trigger the button, span, Div's Click event in turn when the button is clicked, and neither the button nor span defines the event method, so whether the click button, span, or div will bubble to the DIV's Click event, Then we can tell from the target property above that it was triggered by that node. Please see:

What's the good of being in trouble? Let's take a closer look at this bubbling node Click event, did you find out that we just took one of the outermost div elements through getElementById, and we only used one method ( though the logic in the method is more complex ). This is just 3 elements, what if there are 30 of them? Even hundreds? We define only the outermost elements, which reduces the number of DOM references ( which directly reduces the time it takes to retrieve the elements ) and also reduces the memory footprint. Directly improves performance. ( Although there are times when we don't define events like this, I rarely define events myself, which may be a habit problem.) >_<)

This is a learning record, not a tutorial. You can point out mistakes, but don't be mean.

Transfer from personal blog: http://www.haojima.net/zhaopei/531.html

This article has been synchronized to the catalog index: learn JavaScript step

Learn the basics of JavaScript in one step (8): A Story in detail

Related Article

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.