Differences between return false, E. preventdefault (), E. stoppropagation () in jquery

Source: Internet
Author: User

E. stoppropagation () prevents event bubbles

<Head>
   <Title> </title>
   <SCRIPT src = "scripts/jquery-1.4.1.js" type = "text/JavaScript"> </SCRIPT>
</Head>
<Body>
   <Table>
       <Tr>
           <TD> <span> bubble event test </span> </TD>
       </Tr>
   </Table>
</Body>

Let's first look at this Code:

   <SCRIPT type = "text/JavaScript">
       $ (Function (){
           $ ("Table"). Click (function () {alert ("Table alert ");});
           $ ("TD"). Click (function () {alert ("TD alert ");});
           $ ("Span"). Click (function (){
                   Alert ("span alert ");
           });
       });
   </SCRIPT>

We can see the following situation: Span alert-> TD alert-> table alert. This is called event bubbling. Events are triggered from bottom to top, from inside to outside.

Sometimes we don't want event bubbles. What should we do?

   <SCRIPT type = "text/JavaScript">
       $ (Function (){
           $ ("Table"). Click (function () {alert ("Table alert ");});
           $ ("TD"). Click (function () {alert ("TD alert ");});
           $ ("Span"). Click (function (e ){
                   Alert ("span alert ");    
                   E. stoppropagation ();
           });
       });
   </SCRIPT>

To obtain event-related information, add an e object to the anonymous method. e is the event object.

 

E. preventdefault () blocks default event behavior.

$ ("A"). Click (function (e ){
    Alert ("forbidden by default ");
    E. preventdefault ();
});

<A href = "http://www.baidu.com"> test </a>

 

 

Return false is equivalent to calling e. preventdefault () and E. stoppropagation () at the same time ()

 

In addition to blocking default behaviors, return false also prevents event bubbles. If you have a copy of jquery source code, you can view the following code:

If (ret = false ){
Event. preventdefault ();
Event. stoppropagation ();
}

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.