Return false; and e. preventDefault ();

Source: Internet
Author: User

Have you ever seen those two things (in the title) being used in jQuery? Here is a simple example:
Copy codeThe Code is as follows:
$ ("A"). click (function (){
$ ("Body"). append ($ (this). attr ("href "));
Return false;
}

That code wocould append the href attribute as text to the body every time a link was clicked but not actually go to that link. the return false; part of that code prevents the browser from grouping the default action for that link. that exact thing cocould be written like this:
Copy codeThe Code is as follows:
$ ("A"). click (function (e ){
$ ("Body"). append ($ (this). attr ("href "));
E. preventDefault ();
}

So what's the difference?


The difference is that return false; takes things a bit further in that it also prevents that event from propagating (or "bubbling up") the DOM. the you-may-not-know-this bit is that whenever an event happens on an element, that event is triggered on every single parent element as well. so let's say you have a box inside a box. both boxes have click events on them. click on the inner box, a click will trigger on the outer box too, unless you prevent propagation. like this:

Demo address: http://css-tricks.com/examples/ReturnFalse/
So in other words:
Copy codeThe Code is as follows:
Function (){
Return false;
}

// IS EQUAL

Function (e ){
E. preventDefault ();
E. stopPropagation ();
}

It's all probably a lot more complicated than this and articles like this probably explain it all a lot better.


Refer:

1. The difference between 'Return false; 'and 'E. preventDefault ();'
2. Event order

Package and download test code

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.