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

May 16, 2016 pm 05:17 PM
false return

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

What is the execution order of return and finally statements in Java? What is the execution order of return and finally statements in Java? Apr 25, 2023 pm 07:55 PM

Source code: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#Output The output of the above code can simply conclude: return is executed before finally. Let's take a look at what happens at the bytecode level. The following intercepts part of the bytecode of the case1 method, and compares the source code to annotate the meaning of each instruction in

How does Vue3 use setup syntax sugar to refuse to write return How does Vue3 use setup syntax sugar to refuse to write return May 12, 2023 pm 06:34 PM

Vue3.2 setup syntax sugar is a compile-time syntax sugar that uses the combined API in a single file component (SFC) to solve the cumbersome setup in Vue3.0. The declared variables, functions, and content introduced by import are exposed through return, so that they can be used in Vue3.0. Problems in use 1. There is no need to return declared variables, functions and content introduced by import during use. You can use syntactic sugar //import the content introduced import{getToday}from'./utils'//variable constmsg='Hello !'//function func

Use the return keyword in JavaScript Use the return keyword in JavaScript Feb 18, 2024 pm 12:45 PM

Usage of return in JavaScript requires specific code examples In JavaScript, the return statement is used to specify the value returned from a function. Not only can it be used to end the execution of a function, it can also return a value to the place where the function was called. The return statement has the following common uses: Return a value The return statement can be used to return a value to the place where the function is called. Here is a simple example: functionadd(a,b){

Detailed explanation of JavaScript function return values ​​and return statements Detailed explanation of JavaScript function return values ​​and return statements Aug 04, 2022 am 09:46 AM

JavaScript functions provide two interfaces to interact with the outside world. The parameters serve as the entrance to receive external information; the return value serves as the outlet to feed back the operation results to the outside world. The following article will take you to understand the JavaScript function return value and briefly analyze the usage of the return statement. I hope it will be helpful to you!

How to use return statement in JavaScript How to use return statement in JavaScript Feb 26, 2024 am 09:21 AM

How to use return in JavaScript requires specific code examples. In JavaScript, return is a very important keyword. It is usually used to return a value in a function or end the execution of a function. The return statement is used to return a value to the caller of the function and terminate the execution of the function. The return statement can be used anywhere in a function and can return any JavaScript data type, including numbers, strings, booleans,

How to use return value in Python How to use return value in Python Oct 07, 2023 am 11:10 AM

Python return value return usage is that when the function executes the return statement, execution will stop immediately and the specified value will be returned to the place where the function was called. Detailed usage: 1. Return a single value; 2. Return multiple values; 3. Return a null value; 4. End the execution of the function early.

SpringBoot interceptor returns false to show how to solve cross-domain problems SpringBoot interceptor returns false to show how to solve cross-domain problems May 13, 2023 pm 05:10 PM

The project recently added an IP black and white list function. I found that if the IP filtering interceptor returns false, the front end will display cross-domain. After trying to modify the MVC configuration class, I found that it still didn't work. Finally, I added a judgment to the interceptor @OverridepublicbooleanpreHandle. (HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsIOException{//-----------Just add this-----------if(!(handlerinstanceo

See all articles