A brief analysis of the correct use of return false

  • 2020-03-26 23:07:15
  • OfStack

Probably the first example you'll see when you first learn about jQuery event handling is how to prevent the browser from performing default behavior, such as this code that demonstrates the click event:

$("a.toggle").click(function () {  
    return false; // Prevent browser from visiting `#`  

This function USES toggle to show or hide #mydiv, and then prevents the browser from continuing to access the link specified in the href.

Examples like the one above can get users into the bad habit of using "return false" to prevent the browser from performing the default behavior. In this article, I'll discuss two very important topics about preventing the browser from performing the default behavior:

The & # 8226; Choose the right way: Return false or preventDefault, stopPropagation or stoptoken propagation
The & # 8226; Choose the right place, start, end, or somewhere in between: In which part of the event callback should you cancel the browser's default behavior?

Note: When I mentioned in this article the event bubbling (event bubbling), I want to express that most events are on the initial DOM first, and then through the DOM tree, trigger on every level of the parent element, the event will not bubble on child or brother node (when the event bubbling down, we call it the event capture (event capturing)), here you can learn more about the event bubbles and capture is introduced.

Choose the right way

The reason "return false" is so misused is because it looks like it's done what we asked it to do, the browser will no longer redirect us to the link in the href, and the form will no longer be submitted, but what's wrong with that?

What does "return false" do?

Every time you call "return false," it actually does three things:

The & # 8226; Event. The preventDefault ();
The & # 8226; Event. StopPropagation ();
The & # 8226; Stops the callback function execution and returns immediately.
"Wait!" you cry! I just want the browser to stop performing the default behavior, and I don't need it to do two more things.

The only thing that prevents the browser from continuing with the default action is preventDefault. Unless you want to stop the bubbling, using return false is a huge risk to your code.

This is the HTML we used to demonstrate:

<div class="post">  
<h2><a href="http://jb51.net">My Page</a></h2>  
<div class="content">  
    Teaser text...  
<div class="post">  
<h2><a href="http://jb51.net">My Other Page</a></h2>  
<div class="content">  
    Teaser text...  

Now suppose we want to dynamically load the article into the div.contentd when the user clicks on the title of the article:

jQuery(document).ready(function ($) {  
  $("div.post h2 a").click(function () {  
    var a    = $(this),  
    href = a.attr('href'), // Let jQuery normalize `href`,  
    content  = a.parent().next();  
    content.load(href + " #content");  
    return false; // "cancel" the default behavior of following the link  

This code works (at least for now), but if we go this route, if I want to add an active class to a div.post element when the user clicks on it (or any of its children), I need to add one to div.post Click the callback:

// Inside Document Ready:  
var posts = $("div.post");  
  posts.click(function () {  
  // Remove active from all div.post  
  // Add it back to this one  

Now, if we click on the title of a post, will this code work? The answer is no, because we used return false in the title click callback instead of what we should have, "return false" equals event.preventdefault (); Add event. StopPropagation (); , so the event bubble is terminated, the click event is not bubbled to div.post, and the event callback we added to it is certainly not called.

It's even worse when we mix it with live or delegate events.

$("a").click(function () {  
  // do something  
  return false;  

$("a").live("click", function () {  

So what do we really need?

The preventDefault ()

Most of the time, when you use return false, what you really need is e.reventdefault (). To use e.p.ventdefault, you need to make sure you pass the event parameter to your callback function (in this case, the e) :

$("a").click(function (e) {  
  // e == our event data  

It will do all the work for us, but it won't stop the parent node from continuing to handle the events. Remember, the less restrictions you put in your code, the more flexible your code will be, and the easier it will be to maintain.

StopPropagation ()

StopImmediatePropagation ()

This method will stop an event and continue to execute, even if other handlers are bound to the current object, all the events bound to an object will be executed in the order of binding. See the following example:

$("div a").click(function () {  
  // Do something  

$("div a").click(function (e) {  
  // Do something else  

$("div a").click(function () {  

$("div").click(function () {  

This example may seem awkward to you, yes, but sometimes it does happen. If your code is very complex, it is possible for different widgets and pluginto add events to the same object.

Return false

You can use "return false" only if you require both preventDefault and stopPropagation, and your code accepts that it will not stop executing the browser's default behavior until your callback completes. But I strongly recommend that you don't use this method in your demo code for other jQuery developers, because it causes more misuse, and only use "return false" if you're sure you have to.

Choose the right location

If you use "return false", it will only cancel the default behavior of the browser at the end of the execution of your callback function, but with e.p. reventDefault, we have more options, it can stop the default action of the browser at any time, regardless of which part of the function you put it in.

1. Development stage You should always put it in the first row. The last thing you want to do is debug a form into an ajax submission and it's already committed the old way.

3. In the product phase, If the function is designed with JS, it should still be on the first line.

Remember, don't have to is the function of the first row, but the sooner the better, the principle is: if the function of the function is achieved by JS (not involving the interaction of a service), there would be no need to consider, in this case, add in the first row can prevent the # character appear in the URL, but obviously, you should add some error handling code as much as possible, in order to prevent the users become overwhelmed when wrong.


Related articles: