When and why to return false
in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
Er ... how about in a boolean function to indicate 'not true'?
When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead.
For more take a look at the MDN docs page for
return
.Often, in event handlers, such as
onsubmit
, returning false is a way to tell the event to not actually fire. So, say, in theonsubmit
case, this would mean that the form is not submitted.I'm guessing that you're referring to the fact that you often have to put a 'return false;' statement in your event handlers, i.e.
The 'return false;' in this case stops the browser from jumping to the current location, as indicated by the href="#" - instead, only doSomeFunction() is executed. It's useful for when you want to add events to anchor tags, but don't want the browser jumping up and down to each anchor on each click
return false using only if you have some worng in function (by some test) or you want to stop some function, example use return false in end "onsubmit"
When you want to trigger javascript code from an anchor tag, the onclick handler should be used rather than the javascript: pseudo-protocol. The javascript code that runs within the onclick handler must return true or false (or an expression than evalues to true or false) back to the tag itself - if it returns true, then the HREF of the anchor will be followed like a normal link. If it returns false, then the HREF will be ignored. This is why "return false;" is often included at the end of the code within an onclick handler.