javascript:只有在检测到“返回假”时才执行 onsubmit
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12449051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript: does onsubmit only execute when it detects a "return false"
提问by user1666411
i dont quite understand how the onsubmit="return validate()"
works.
why do i have to return
the function? does this work only when it detects a return false
from the statement?
我不太明白是如何onsubmit="return validate()"
工作的。为什么我必须使用return
该功能?仅当它return false
从语句中检测到 a 时才有效吗?
<script type="text/javascript">
function validate() {
if ((document.example2.naming.value == "") || (document.example2.feed.value == "")) {
alert("You must fill in all of the required .fields!");
return false;
}
else {
return true;
}
</script>
<form name="example2" onsubmit="return validate()">
<input type="submit" name="B1" value="Submit">???????
回答by Ian
Using return
for onsubmit
determines whether the form actually submits or not (true
or false
, respectively). This is useful for Javascript when you want to do something specific before allowing the form to submit or not. For example, like the code you provided, the point is to stop the form from submitting if the form isn't valid - if a certain field is blank. The important part is that you need to include return
in the onsubmit part, as well as actually returning true
or false
in the function you call. This is because the behavior for onsubmit
is to always complete unless you return false
. So when you do something like:
使用return
foronsubmit
确定表单是否实际提交(分别为true
或false
)。当您想在允许或不提交表单之前做一些特定的事情时,这对 Javascript 很有用。例如,就像您提供的代码一样,如果表单无效 - 如果某个字段为空,则停止表单提交。重要的部分是您需要包含return
在 onsubmit 部分,以及实际返回true
或false
您调用的函数中。这是因为onsubmit
除非您返回,否则for 的行为将始终完成false
。因此,当您执行以下操作时:
onsubmit="validate();"
nothing is returned (because of the lack of return
) - so the function is run but that's it, so the form is submitted. When you add return
, then the submitting depends on the return value - what's returned from the function. If you don't use return
, it doesn't matter what the validate
function returns, because the result of validate
is not actually returned to onsubmit
.
什么都没有返回(因为缺少return
) - 所以函数被运行,但就是这样,所以表单被提交。当您添加时return
,提交取决于返回值 - 从函数返回的内容。如果不使用return
,则validate
函数返回什么并不重要,因为 的结果validate
实际上并未返回到onsubmit
。
回答by Jo?o Silva
When return
ing false
, you preventthe form
from being submitted. Otherwise, the form would be submitted, even though it may have validation errors, e.g., the feed
value was empty.
当return
荷兰国际集团false
,就防止了form
被提交。否则,表单将被提交,即使它可能有验证错误,例如,feed
值为空。
On the other hand, if you return true
, the form data will be submitted to the URL defined by the action
attribute.
另一方面,如果你return true
,表单数据将被提交到action
属性定义的 URL 。