Native JavaScript detailed

Source: Internet
Author: User

jquery This write less does more framework, with more than will inevitably to the native JS above his business.

       Side dishes actually do not want to write this blog, seemingly very elementary appearance, but see the network even the native JS event binding and lifting are said not understand, or decided to science a bit.        First of all, the dishes understand is not a lot, just put my ideas and share with you. The    dom0 event model          Event model is evolving, and the early event model is called the DOM0 level.      &NBSP;DOM0 event model, supported by all browsers.        Registering event names directly on DOM objects is DOM0 notation, such as:  1 document.getElementById ("test"). onclick = function (e) {};      means registering an onclick event. Of course, it and this writing is a meaning:  1 document.getElementById ("test") ["onmousemove"] = function (e) {};      It's nothing. is only two ways to access the properties of JS object, [] The form is mainly to solve the property name is not a valid identifier, such as: object.123 positive error, but object["123"] to avoid this problem, at the same time, [] The wording, also JS wrote live, You can dynamically bind an event at run time by representing the property name with a string.        When the event is triggered, a parameter e is passed by default, indicating the event object, through E, we can get a lot of useful information, such as the coordinates of the click, the DOM element that triggered the event, and so on.        DOM0-based events, for the same DOM node, you can only register one, and the same event that is registered behind will overwrite the previously registered. For example:   1 var btn = document.getElementById ("Test"), 2 3 btn.onmousemove = function (e) {4   alert ("OK"); 5};6 7 btn["onmousemove"] = function(e) {8   alert ("Ok1"); 9};       results output ok1.        Then say this again. When an event is triggered, this refers to which DOM object the event is triggered on. For example:   1 var btn = document.getElementById ("Test"), 2 3 btn.onmousemove = function (e) {4   alert ( This.id); 5};       result output test. Because the event is registered on the DOM node with the ID test, this, of course, represents the DOM node, which is understood to be called by the DOM node when the event is triggered.        So, to dismiss the event is quite simple, only need to register the event again, set the value to NULL, for example:  1 var btn = document.getElementById ("Test"); 2  3 Btn.onclick = function (e) {4   alert ("OK"), 5};6 7 Btn.onclick = null;       principle is last registration Event to overwrite before the last registered event is set to NULL, the event binding is also dismissed.        Things are not over yet, the DOM0 event model also involves events written directly in HTML. For example:  1 <div id= "test" class= "test" onclick= "exec ()" ></div>      events registered in this way also follow the overriding principle, The same can only be registered one, the last one takes effect.        The difference is that registering an event like this is a dynamic call to a function (a bit of eval), so the event object is not passed in, and this is pointing to window, which is no longer the DOM object that triggered the event.    dom2 Event Model        &NBSP;DOM2 Event Model phaseFor DOM0, the side dishes only understand the following two points:             &NBSP;DOM2 supports the same DOM element to register multiple same-event events.             dom2 added the concept of capture and bubbling.        &NBSP;DOM2 events through AddEventListener and RemoveEventListener management, of course, this is the standard.        But IE8 and the following versions of the browser, amuse themselves, made the corresponding attachevent and detachevent, because of the side dishes Caishuxueqian, this article does not discuss.       addeventlistener is of course the registration event, she has three parameters, namely: "Event name", "Event callback", "Capture/bubble". For example:   1 var btn = document.getElementById ("test"); 2 3 btn.addeventlistener ("click", Function (e) {4   Alert ("OK"); 5}, False);       Event name don't say more than DOM0, get rid of the front.        Event callbacks are also well understood, event triggers have to notify you! Callbacks, like DOM0, pass in an event parameter by default, and this is the DOM node that triggers the event.        The last parameter is a Boolean, true represents the capture event, and false represents the bubbling event. Actually very good understanding, first to a:           means that an element triggered an event, the first to be notified is window, then the document, in turn, This process is captured until the element (the target element) that actually triggered the event. Next, the event bubbles from the target element, and then sequentially out until the Window object, the process is bubbling.      &NBSP; Why do you design this? This seems to be due to the deep historical origins, the side dish also does not understand, will not utter nonsense.        As you can see, the capture event is triggered before the bubbling event.        Suppose there is such an HTML structure:  1 <div id= "test" class= "test" >2   <div id= "Testinner" class= "Test-inner" ></div>3 </div>      Then we register two click events on the outer Div, capturing events and bubbling events, the code is as follows:    1 var btn = document.getElementById ("test")  2  3//Capture event  4 Btn.addeventlistener (" Click ", Function (e) { 5   alert (" Ok1 ");  6}, True);  7  8//bubbling event  9 Btn.addeventlistener ("click", Function (e) {  alert ("OK"), one}, False);       Finally, click on the inner Div, Eject Ok1 First, then eject OK. Combined with the above schematic, the outer div is equivalent to the body in the diagram, the inner div is equivalent to the bottom div in the diagram, proving that the capture event executes first and then the bubbling event is executed.        Why emphasize clicking on the inner div? Because the DOM element that really triggers the event must be an inner layer, the outer DOM element has the opportunity to simulate the capture event and bubbling event, as seen from the schematic.        If capture events and bubbling events are registered on the DOM element that really triggers the event?       html structure ibid., JS code as follows:    1 var btninner = document.getElementById ("Testinner");  2   3//Bubbling event  4 Btninner.addeventlistener ("click", Function (e) { 5   alert ("OK");  6}, False); &NBSP;7&NBSP;&NBSP;8//Capture event  9 Btninner.addeventlistener ("click", Function (e) {  alert ("Ok1");}, True);        Of course, click on the inner Div, the result is the first popup OK, and then pop Ok1. In theory, the capture event should be triggered first, that is, the Ok1 is popped first, but here it is special, because we are registering on the DOM element that actually triggers the event, which is equivalent to registering on the div in the diagram, which shows the DOM element that really triggered the event, the end of the capture event, and the starting point of the bubbling event. So here is not a distinction between events, which first registered, which is executed first. In this case, the bubbling event is first registered, so it is executed first.        This applies to multiple events of the same kind, such as registering 3 bubbles at a single event, then the order of execution follows the order of registration, first the registration is executed first. For example:    1 var btninner = document.getElementById ("Testinner");  2  3 Btninner.addeventlistener ("click", Function (e) { 4   alert ("OK");  5}, False);  6  7 Btninner.addeventlistener ("click", Function (e) { 8   alert ("Ok1");  9}, False); 10 11 Btninner.addeventlistener ("click", Function (e) {  alert ("Ok2");;       The results are, of course, pop-up OK, Ok1, Ok2.        To further understand the event model, there is aScene, if the outer div and the inner Div Register the capture event at the same time, then click on the inner Div, the outer div event must be triggered first, the code is as follows:    1 var btn = document.getElementById (" Test "),  2 var btninner = document.getElementById (" Testinner ");  3  4 Btninner.addeventlistener (" Click ", Function (e) { 5   alert (" OK ");  6}, True);  7  8 btn.addeventlistener (" click ", Function (e) { 9   alert ("Ok1"), true);       The result is a pop-up Ok1 first.        If the outer div and the inner div are registered bubbling events, when clicking on the inner Div, it must be the inner DIV event first executed, the same principle.        Attentive readers will find that for div nesting cases, if you click on the inner Div, the outer div will trigger the event, which seems to be problematic!        Click is the inner Div, but the outer div event also triggers, which is really a problem.        In fact, when an event is triggered, it is passed to an event object by default, as mentioned above, there is a method on this event object: Stoppropagation, this method can prevent bubbling, This allows the outer div to receive no events. The code is as follows:    1 var btn = document.getElementById ("Test"),  2 var btninner = document.getElementById (" Testinner ");  3  4 btn.addeventlistener (" click ", Function (e) { 5   alert (" Ok1 ");  6}, False;  7  8 Btninner.addeventlistener ("click", Function (e) { 9  //Block bubble e.stoppropagation (); 11   Alert ("OK"), and false);       Finally talk about how to dismiss the event. Dismiss event Syntax: Btn.removeeventlistener ("event name", "Event callback", "Capture/bubble");       This is the same as the parameters of the binding event, which is described in detail under:                The event name, which means which event to dismiss.            The   event callback is a function that must be the same as the function that registers the event.              Event Type, Boolean, which must be the same type as when registering the event.          That is, the name, callback, type, three together decide which event to release, indispensable. For example:    1 var btn = document.getElementById ("Test"), &NBSP;2//The callback is stored in the variable  3 var fn = function (e) {  4   alert ("OK");  5}; 6//Bind  7 Btn.addeventlistener ("Click", FN, false); 8   9//release of Btn.removeeventlistener ("Click", FN, false);       The event to be registered can be lifted, the callback function must be saved, otherwise it cannot be lifted.    dom0 and DOM2 mixed          ThingsIt was very messy, this is a mixed use, but also let people live ...        Don't be afraid, mixed use is no problem, DOM0 model and DOM2 model each follow their own rules, do not affect each other.        On the whole, which is still the first to register, which is executed first, the other is nothing.             At this point, the native JS event has been talked about almost, side dishes only know these, welcome readers to supplement other knowledge points.        In practice, real pros don't really register for so many events, and in general, simply register an event in the outermost DOM element, and then find the DOM element that really triggered the event by capturing and bubbling the mechanism. Finally, the callback is invoked based on the information provided by the DOM element that triggered the event.        That is to say, experts manage events on their own without relying on a browser to manage them, so that can improve efficiency and ensure compatibility, which is what jquery does.

Native JavaScript detailed

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.