Home > Web Front-end > JS Tutorial > A brief analysis of the correct use of return false_javascript skills

A brief analysis of the correct use of return false_javascript skills

WBOY
Release: 2016-05-16 17:17:42
Original
1067 people have browsed it

Perhaps when you first started learning about jQuery event handling, the first example you saw was about how to prevent the browser from executing the default behavior, such as the following code demonstrating a click event:

Copy code The code is as follows:

$("a.toggle").click(function () {
$( "#mydiv").toggle();
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 above will make users develop the bad habit of using "return false" to prevent the browser from executing the default behavior. In this article, I will discuss two very important ways to prevent the browser from executing the default behavior. Important topics:

•Choose the right method: return false or preventDefault, stopPropagation or stopImmediatePropagation
•Choose the appropriate position, start, end, or middle Somewhere: In which part of the event callback should you cancel the browser's default behavior?

Note: When I mention event bubbling in this article, what I want to express is that most events occur initially It is triggered on the DOM, and then goes up through the DOM tree, triggering on each level of parent elements. The event will not bubble up on sibling nodes or child nodes (when the event bubbles down, we call it event capture (event capturing)), you can learn more about event bubbling and capturing here.

Choose the right method

The reason why "return false" is so misused is because it looks like it has completed the job we gave it, the browser will no longer redirect us to the link in the href, and the form will no longer redirect us to the link in the href. Will continue to be submitted, but what's wrong with doing this?

What exactly does "return false" do?

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

•event.preventDefault();
•event.stopPropagation();
•Stop callback function execution and return immediately.
"Wait a minute", you yelled! I just want the browser to stop executing the default behavior, I don't need it to do the other 2 things.

Of these 3 things, only preventDefault is used to prevent the browser from continuing to perform the default behavior. Unless you want to stop event bubbling, using return false will plant a lot of hidden dangers for your code. Let's go through a Let’s see the consequences of such misuse with a real example:

This is the HTML we used to demonstrate:

Copy the code The code is as follows:


My Page



Teaser text...



My Other Page

Teaser text...



Now suppose we want to dynamically load the article into div.contentd when the user clicks on the article title:
Copy code The code is 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 fine (at least for now), but if we continue along this line of thought, what if I want to give it a message when the user clicks on a div.post element (or any of its children) Adding an active class, I need to add a click callback to div.post:
Copy code The code is 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, will 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" is equal to event.preventDefault(); plus event.stopPropagation();, so the event bubbling is terminated. , the click event will not bubble up to div.post, and the event callback we added for it will of course not be called.

If we mix it with live or delegate events, the situation will be worse.

Copy code The code is as follows:

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

$("a").live("click", function () {
// THIS WON 'T FIRE
});

So what do we really need?

preventDefault()

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

Copy code The code is 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 events. Remember, the less restrictions you put in the code , the more flexible your code is and the easier it is to maintain.

stopPropagation()

But there are situations where you may need to stop event bubbling, let’s look at the following example:

Copy code The code is as follows:


Normal text and then a link and then more text. (For example, changing the background or something), but it cannot affect the user's behavior of clicking a link (from a usability perspective, this example is not very good, you may not want anything to happen when the user clicks elsewhere).



Copy code
The code is as follows:$("div.post").click(function () { // Do the first 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 With return false, the div's click event will not be fired, but the user will not reach the link they clicked.


stopImmediatePropagation()

This method will stop an event from continuing to execute. Even if other processing functions are bound to the current object, all events bound to an object will be executed in the binding order. Take a look at the following example:


Copy code

The code is 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 may think this example looks awkward, yes, but it does happen sometimes. If your code is very complex, then different widgets and plugins may add events on the same object. , if you encounter this situation, it is necessary for you to understand and use stopImmediatePropagation.

return false

Only if you need preventDefault and stopPropagation at the same time, and your code can accept the browser's default behavior of not stopping until your callback execution is completed, then you can use "return false". But I strongly recommend that you don't use this method in demo code written for other jQuery developers, because it will lead to more misuse, and only use "return false" when you are sure that it is absolutely necessary.

Choose the appropriate location

If you use "return false", it will only cancel the browser's default behavior after your callback function is executed, but with e.preventDefault, we have more options, it can stop the browser at any time Performs the default action regardless of where in the function you place it.

1. During the development phase, you should always put it on the first line. The last thing you want to do may be that when you are debugging to change a form to ajax submission, it has already been submitted according to the old method.

2. Product stage, If you use progressive enhancement, put it at the end of the callback, or at the logical end point. If you use progressive enhancement on a normal page, Then you need to consider on the server side how to handle the link's click event and the form's submit event if the browser does not support JS (or is disabled). The advantage here is that we do not consider the case of turning off JS, only the madness when supporting js. If your callback code makes an error and throws an exception, let us look at the following code:

Copy code The code is as follows:

var data = {};
$("a").click(function (e ) {
e.preventDefault(); // cancel default behavior
// Throws an error because `my` 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 Let’s look at the same event and the effect of placing the preventDefault call at the bottom:
Copy the code The code is as follows:

>
var data = {};
$("a").click(function (e) {
// Throws an error because `my` is undefined
$ ("body").append(data.my.link);

// This line is never reached, and your website
// falls back to using the `href` instead of this
// "cool" broken JavaScript!
e.preventDefault(); // cancel default behavior
});

This also works for form submission, you can be better Don't expect your code to always work properly. It's better to have the right response when an error occurs than to assume that your code won't go wrong.

3. In the product stage, If the function is designed in JS, it should be placed in the first line.

Remember, it doesn’t have to be the first line of the function, but the earlier the better. The principle here is: if the function of the function is implemented through JS (does not involve server-side interaction), then there is no need to consider compatibility. In this case, adding it on the first line will prevent the # character from appearing in the URL, but obviously you should still add as much error handling code as possible to prevent the user from becoming confused when an error occurs.

Conclusion

I hope this article conveys enough information for you to make the right choice if you need to prevent your browser from performing default behavior. Remember, only use "return false" if you really know what you are doing, and make sure you are calling the corresponding code at the correct place in the function. Finally, keep your code as flexible as possible and try not to use "return false" again!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template