javascript:onsubmit只在检测到“return false”时才执行 [英] javascript: does onsubmit only execute when it detects a "return false"
问题描述
我不太明白 onsubmit =return validate()
是如何工作的。
为什么我必须返回
这个函数?仅当它从语句中检测到 return false
时才能工作吗?
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?
<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">
推荐答案
使用返回
获取 onsubmit
确定表单是否实际提交(分别为 true
或 false
)。当您想要在允许表单提交之前执行特定操作时,这对Javascript很有用。例如,与您提供的代码一样,关键是如果表单无效,则停止表单提交 - 如果某个字段为空。重要的是你需要在onsubmit部分包含 return
,以及实际返回 true
或<$您调用的函数中的c $ c> false 。这是因为除非您返回 false
,否则 onsubmit
的行为将始终完成。所以当你做类似的事情时:
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:
onsubmit="validate();"
没有返回任何内容(因为缺少返回
) - 所以函数运行但是就是这样,所以提交了表单。当你添加 return
时,提交取决于返回值 - 从函数返回的内容。如果你不使用 return
,那么返回 validate
函数是什么并不重要,因为验证
实际上并未返回 onsubmit
。
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
.
这篇关于javascript:onsubmit只在检测到“return false”时才执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!