本文介绍了使用表单验证:为什么onsubmit =" return functionname()"而不是onsubmit =" functionname()"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题非常明显。我不明白返回在以下代码中做了什么:

The question is pretty self-explanatory. I don't understand what the return is doing in the following code:

<form onsubmit="return somefunction()">


推荐答案

您需要返回以便传递true / false直到表单的提交事件(查找此事件并在出现错误时阻止提交)。

You need the return so the true/false gets passed up to the form's submit event (which looks for this and prevents submission if it gets a false).

让我们看看一些标准的JS:

Lets look at some standard JS:

function testReturn() { return false; }

如果您只是在任何其他代码中调用它(无论是onclick处理程序还是其他地方的JS)它会返回false,但你需要用这个值做一些事情。

If you just call that within any other code (be it an onclick handler or in JS elsewhere) it will get back false, but you need to do something with that value.

...
testReturn()
...

在该示例中,返回值即将返回,但什么也没发生用它。你基本上是说执行这个函数,我不在乎它返回什么。相反,如果你这样做:

In that example the return value is coming back, but nothing is happening with it. You're basically saying execute this function, and I don't care what it returns. In contrast if you do this:

...
var wasSuccessful = testReturn();
...

然后你已经用返回值做了一些事情。

then you've done something with the return value.

同样适用于onclick处理程序。如果你只是在onsubmit中调用没有返回的函数,那么你就是说执行此操作,但如果返回false则不要阻止该事件。这是表示在提交表单时执行此代码的一种方式,但不要让它停止事件。

The same applies to onclick handlers. If you just call the function without the return in the onsubmit, then you're saying "execute this, but don't prevent the event if it return false." It's a way of saying execute this code when the form is submitted, but don't let it stop the event.

一旦你添加了回报,你就是说您正在调用的内容应该确定事件(提交)是否应该继续。

Once you add the return, you're saying that what you're calling should determine if the event (submit) should continue.

此逻辑适用于HTML中的许多onXXXX事件(onclick,onsubmit,onfocus等) )。

This logic applies to many of the onXXXX events in HTML (onclick, onsubmit, onfocus, etc).

这篇关于使用表单验证:为什么onsubmit =&quot; return functionname()&quot;而不是onsubmit =&quot; functionname()&quot;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 02:13