Unlike the other answers, return false
is only part of the answer.(与其他答案不同,返回false
只是答案的一部分 。)
Consider the scenario in which a JS error occurs prior to the return statement...(考虑在return语句之前发生JS错误的情况...)
html(html)
<form onsubmit="return mySubmitFunction(event)">
...
</form>
script(脚本)
function mySubmitFunction()
{
someBug()
return false;
}
returning false
here won't be executed and the form will be submitted either way.(返回false
将不会执行,并且将以任何一种方式提交表单。) You should also call preventDefault
to prevent the default form action for Ajax form submissions.(您还应该调用preventDefault
以阻止Ajax表单提交的默认表单操作。)
function mySubmitFunction(e) {
e.preventDefault();
someBug();
return false;
}
In this case, even with the bug the form won't submit!(在这种情况下,即使存在错误,表单也不会提交!)
Alternatively, a try...catch
block could be used.(或者,可以使用try...catch
块。)
function mySubmit(e) {
e.preventDefault();
try {
someBug();
} catch (e) {
throw new Error(e.message);
}
return false;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…