JS Block event bubbling stoppropagation (), cancelbubble, Preventdefault (), Return false analysis

Source: Internet
Author: User

Event bubbling, for example:

<li>    <a href= ' http://www.baidu.com ' > click a</a></li><script>    $ (' Li ') . Click (function  () {        alert (' clicked on Li ');    });    $ (' a '). Click (function  () {        alert (' clicked a ');    }); </script>

When you click on A, will first pop ' click a ', then pop ' click Li ', and finally jump to Baidu. The simple understanding is that the event of the child element is executed before the event of the parent element, as opposed to the event capture.

There are times when we do not want events of the parent element to occur, only the events of the child elements, and then we need to block the event bubbling. There are a few ways to analyze it separately:

1, event.stoppropagation ();

2, event.cancelbubble = true;

3, Event.preventdefault ();

4, return false;

One, event.stoppropagation ();

<script>    $ (' Li '). Click (function  () {        alert (' click on Li ');    });    $ (' a '). Click (function  (event) {        alert (' clicked a ');        Event.stoppropagation ();    }); </script>

Perfect prevents the LI element from bubbling and does not affect the event of a. The effect is: First Pop ' click a ', and then jump Baidu

Note: Before see said is incompatible IE8 and a bit, pro-test IE6 above no problem, such as wrong, hope points out.

Second, event.cancelbubble = true;

<script>    $ (' Li '). Click (function  () {        alert (' click on Li ');    });    $ (' a '). Click (function  () {        alert (' clicked a ');        Console.log (event);         true ;    }); </script>

The use of cancelbubble requires attention:

The event is the MouseEvent of the window, where Console.log prints: MouseEvent {istrusted:true, screenx:55, screeny:90, clientx:55, clienty:29 ... },

so do not pass event in click events. (Don't do this: $ (' a '). "Click (function (event) {});). The effect is the same as above: First Pop ' click a ', then jump Baidu. Just when the test, as if compatibility is OK.

Third, Event.preventdefault ();

<script>    $ (' Li '). Click (function  () {        alert (' click on Li ');    });    $ (' a '). Click (function  (event) {        alert (' clicked a ');        Event.preventdefault ();    }); </script>

After the execution of the effect: the first pop ' click a ', and then pop ' click Li ', but, do not jump! Do not jump! Do not jump!

In fact, the default English meaning is defaulted, It is not difficult to understand that the page, in addition to performing a listener event will also trigger the browser default action, the execution of the listener event before, triggering the browser default action after.

Preventdefault is not exactly blocking event bubbling, it's just blocking the browser's default action. and Stoppropagation and cancelbubble just stopped the event bubbling and didn't stop

The default action of the browser. When we want to prevent events from bubbling while also blocking the browser's default actions, it is possible to use 2 of them together, the following code:

<script>    $ (' Li '). Click (function  () {        alert (' click on Li ');    });    $ (' a '). Click (function  (event) {        alert (' clicked a ');        Console.log (event);        Event.stoppropagation ();        Event.preventdefault ();    }); </script>

The effect is: only Pop ' click a ', does not jump Baidu link, also does not pop ' click Li '.

(Note: It is best to use stoppropagation to avoid inconsistencies between Preventdefault and Cancelbubble's event objects);

Four, the last one return false;

<script>    $ (' Li '). Click (function  () {        alert (' click on Li ');    });    $ (' a '). Click (function  () {        alert (' clicked a ');         return false ;    }); </script>

Execution effect: only Pop ' click a ', do not jump Baidu link, also do not pop ' click Li '. Heel (Stoppropagation+preventdefault) is an effect.

Exit execution, return false after which all triggering events and actions are not executed. Can sometimes return false be used to replace stopPropagation() and

preventDefault(), such as the example above.

One thing to note: Some people think that return false = stopPropagation() + preventDefault() is actually wrong. return falsenot only prevents events,

You can also return objects, jump out of loops, etc... Convenient one-size-fits-all and less flexible, misuse prone to error.

Post the HTML code for this blog:

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Event bubbling</title></Head><Body>    <ul>        <Li>            <ahref= ' # '>Click a</a>        </Li>    </ul>    <Scriptsrc= "Jquery-1.11.3.min.js"></Script><Script>        $('Li'). Click (function() {alert ('Click on the Li');        }); $('a'). Click (function(Event) {alert ('clicked on a');            Console.log (event);            Event.stoppropagation (); //event.cancelbubble = true;Event.preventdefault (); //return false;        });</Script></Body></HTML>

JS Block event bubbling stoppropagation (), cancelbubble, Preventdefault (), Return false analysis

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.