最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - what's the difference of return true or false here? - Stack Overflow

programmeradmin1浏览0评论
$('form').submit(function() {
  alert($(this).serialize());
  return false;  // return true;
});

what's the difference for this form submission function between return false and true?

$('form').submit(function() {
  alert($(this).serialize());
  return false;  // return true;
});

what's the difference for this form submission function between return false and true?

Share Improve this question asked May 12, 2011 at 12:54 LeemLeem 18.3k39 gold badges112 silver badges164 bronze badges 3
  • return true; is the "default" - it will just continue. If you put return false; then it exits the functions and tells the caller FALSE and stops. TRUE to not stop.. you see. Nobody uses return true in this case. But using return false; is good if you want a click to stop doing its normal behaviour for example. Like in your submit will do alert-- but stop after and not send data.. – Piotr Kula Commented May 12, 2011 at 13:00
  • 2 @ppumkin: I would not say that return true is the default. Having no return statement will return undefined. More correct would be that if the return value is any other than false, the submit event is processed normally. – Felix Kling Commented May 12, 2011 at 13:16
  • Hmm. yea thats why i s said in quotes "" . But by definition a boolean only has 2 states. so if its not false its true. And this is tested when the function ends by the caller. so if undefined is translated to true.. then True is the "default" value – Piotr Kula Commented May 12, 2011 at 13:18
Add a comment  | 

4 Answers 4

Reset to default 8

If you return false from the submit event, the normal page form POST will not occur.

return false, don't do the form's default action. return true, do the form's default action.


It's also better to do

$('form').submit(function(e) {
  alert($(this).serialize());
  e.preventDefault();
});

As already mentioned, returning false stops the event from "bubbling up". If you want the full details, take a look at the API documentation for bind(): http://api.jquery.com/bind/.

"Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object."

return false;  // cancel submit
return true;   // continue submit
发布评论

评论列表(0)

  1. 暂无评论