On the correct use _javascript skill of return False

Source: Internet
Author: User

Perhaps the first example you'll see when you first start learning about jquery event processing is how to prevent the browser from performing the default behavior, such as the following code that demonstrates the Click event:

Copy Code code as follows:

$ ("A.toggle"). Click (function () {
$ ("#mydiv"). Toggle ();
return false; Prevent browser from visiting ' # '
});

This function uses toggle to display or hide the #mydiv, and then prevent the browser from continuing to access the links specified in the href.

Examples like these will allow users to develop the bad habit of using return false to prevent browsers from performing default behavior, and in this article, I'll discuss two very important topics about preventing browsers from performing the default behavior:

• Choose the correct method: return False or Preventdefault,stoppropagation or stopimmediatepropagation
• Choose the right location, start, end, or somewhere in the middle: what part of the event callback should you cancel the browser to perform the default behavior?

Note: When I mention event bubbling in this article, I want to express that most of the events are triggered on the initial dom and then up through the DOM tree, on each level of the parent element, Events do not bubble on sibling nodes or child nodes (when the event bubbles down, we call it event capturing), where you can learn more about event bubbling and capturing.

Choose the Right method

"Return false" is so misused because it looks like it's done the work we gave it, the browser won't redirect us to the link in href, and the form won't be submitted, but what's wrong with that?

What exactly did "return false" do?

When you call "return false" every time, it actually does 3 things:

Event.preventdefault ();
event.stoppropagation ();
• Stop callback function execution and return immediately.
"Wait", you scream! I just want the browser to stop doing the default behavior, and I don't need it to do another 2 things.

The 3 things that are used to prevent browsers from continuing the default behavior are only Preventdefault, unless you want to stop event bubbling, or use return false to put a lot of risk in your code, let's take a real example to see what the consequences of this misuse are:

This is the HTML we used to demonstrate:

Copy Code code as follows:

<div class= "POST" >
<div class= "Content" >
Teaser text ...
</div>
</div>
<div class= "POST" >
<div class= "Content" >
Teaser text ...
</div>
</div>

Now suppose we want to load the article dynamically into DIV.CONTENTD when the user clicks on the title of the article:
Copy Code code as follows:

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 the moment), but if we go along with this idea, if I want to add an active class to the user when they click on a div.post element (or any of its child elements), I need to add a div.post Click Callback:
Copy Code code as follows:

Inside Document Ready:
var posts = $ ("Div.post");
Posts.click (function () {
Remove active from all Div.post
Posts.removeclass ("active");
Add it back to this one
$ (this). AddClass ("active");
});

Now, if we click on the title of a post, does this code work? The answer is no, because we used return false in the click callback of the title instead of what we should use, "return false" equals Event.preventdefault (); plus event.stoppropagation (); , the event bubbling is terminated, the Click event is not bubbling onto the div.post, and the event callback we add to it is certainly not invoked.

This is even worse if we mix it with live or delegate events.

Copy Code code as follows:

$ ("a"). Click (function () {
Do something
return false;
});

$ ("a"). Live ("Click", Function () {
This WON ' T FIRE
});

So what do we really need?

Preventdefault ()

In most cases, when you use return false, what you really need is e.preventdefault (). To use E.preventdefault, you need to make sure that you pass the event parameter to your return function (in this case, that e):

Copy Code code as follows:

$ ("a"). Click (function (e) {
E = our event data
E.preventdefault ();
});

It will do all the work for us, but it will not prevent the parent node from continuing to handle the event, remember that the less restrictive you put in your code, the more flexible your code is and the easier it will be to maintain it.

Stoppropagation ()

But in some cases, you might want to stop the event bubbling, let's take a look at the following example:

Copy Code code as follows:

<div class= "POST" >
Normal text and then a <a href= "Http://jb51.net" >link</a> and then more text.
</div>

Now, let's assume that if you dot a div on a link other than a, we want something to happen (like changing the background or something), but it doesn't affect the behavior of the user clicking a link (from the usability point of view, the example is not very good, you may not want the user to click somewhere else to do anything).
Copy Code code as follows:

$ ("Div.post"). Click (function () {
Do the The thing;
});

$ ("Div.post a"). Click (function (e) {
Don ' t cancel the browser ' s default action
and don ' t bubble this event!
E.stoppropagation ();
});

In this case, if we use the return False,div Click event will not be triggered, but the user will not reach the link they point to.

Stopimmediatepropagation ()

This method stops an event from continuing, even if other handler functions are bound on the current object, and all the events bound to one object are executed in the binding order, looking at the following example:

Copy Code code as follows:

$ ("div a"). Click (function () {
Do something
});

$ ("div a"). Click (function (e) {
Do something else
E.stopimmediatepropagation ();
});

$ ("div a"). Click (function () {
This NEVER fires
});

$ ("div"). Click (function () {
This NEVER fires
});

You might think this example looks awkward, yes, but sometimes it does happen, and if your code is very complex, then different widgets and plugin can add events to the same object, and if that happens, Then it is necessary for you to understand and use stopimmediatepropagation.

return False

You can use "return false" only if you need Preventdefault and stoppropagation at the same time, and your code can be accepted until your callback execution completes to stop the browser from performing the default behavior. But I strongly recommend that you do not use this method in the demo code written to other jquery developers, as this can cause more misuse, and use return false only if you are sure it is not.

Select the appropriate location

If you use "return false", it will only cancel the browser's default behavior at the end of your callback function, but with e.preventdefault, we have more options to stop the browser from performing the default action at any time, regardless of which part of the function you put it in.

1. In the development phase, you should always put it on the first line. The last thing you want to do may be that you are debugging a form into an AJAX submission, but it has been submitted in the old way.

2. In the product phase, if you are using progressive enhancement (progressive enhancement), put it at the end of the callback, or at the logical end, if incremental enhancement is used on an ordinary page, Then you need to consider the server side if the browser does not support JS (or when it is disabled), the linked click event and the form of the submission of the event processing. The advantage here is that we do not consider the case of the shutdown JS, only consider support JS when the crazy, if your callback code error thrown an exception, let us look at the following code:

Copy Code code as follows:

var data = {};
$ ("a"). Click (function (e) {
E.preventdefault (); Cancel default behavior
Throws an error because ' I ' is undefined
$ ("Body"). Append (Data.my.link);
The original link doesn ' t work and the ' cool '
JavaScript has broken. The user is left with nothing!
});

Now, let's look at the same event, put the Preventdefault call at the bottom of the effect:
Copy Code code as follows:

>
var data = {};
$ ("a"). Click (function (e) {
Throws an error because ' I ' is undefined
$ ("Body"). Append (Data.my.link);

This is never reached, and your website
Falls back to using the ' href ' instead of this
"Cool" broken javascript!
E.preventdefault (); Cancel default behavior
});

This is also valid for form submission, you can better handle the error situation, do not expect your code to work properly, the correct response when the error is always better than the assumption that the code is not wrong.

3. In the product phase, if the function of this design JS, it should also be placed in the first line.

Remember, you don't have to be the first line of a function, but the sooner the better, the principle here is: if the function is implemented through JS (not involving server-side interaction), then there is no need to consider compatibility, in which case, add in the first line can prevent the URL to appear in the # character, but obviously, You should also add as many error-handling code as possible to prevent users from being overwhelmed by errors.

Conclusion

I hope this article will convey enough information to make the right choices when you need to prevent browsers from performing the default behavior. Remember to use "return false" only when you really understand what you are doing, and make sure that you are calling the appropriate code in the correct position of the function. Finally, keep your code as flexible as possible, and try not to use "return false" again!

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.