When and why to 'return false' in JavaScri

2019-01-02 15:08发布

When and why to return false in JavaScript?

11条回答
流年柔荑漫光年
2楼-- · 2019-01-02 15:25

Er ... how about in a boolean function to indicate 'not true'?

查看更多
皆成旧梦
3楼-- · 2019-01-02 15:30

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.

查看更多
闭嘴吧你
4楼-- · 2019-01-02 15:32

Often, in event handlers, such as onsubmit, returning false is a way to tell the event to not actually fire. So, say, in the onsubmit case, this would mean that the form is not submitted.

查看更多
孤独总比滥情好
5楼-- · 2019-01-02 15:33

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.

<a href="#" onclick="doSomeFunction(); return false;">...

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

查看更多
余欢
6楼-- · 2019-01-02 15:33

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"

查看更多
倾城一夜雪
7楼-- · 2019-01-02 15:34

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.

查看更多
登录 后发表回答