JavaScript'onclick'事件'返回'关键字功能

Shi*_*i98 47 html javascript return onclick

我是javascript的新手,偶然发现了return关键字.基本上,这两个陈述的区别是什么?

<input type="checkbox" onclick="doAlert()" />
Run Code Online (Sandbox Code Playgroud)

VS

<input type="checkbox" onclick="return doAlert();" />
Run Code Online (Sandbox Code Playgroud)

从本质上讲,两者都返回了相同的结果并调用了函数,但还有更多吗?任何帮助非常感谢:).谢谢!

Gle*_*rie 40

某些html元素具有JS事件,当返回true/false时,它们的行为会有所不同.例如:

<input type='submit' value='Click Me' onSubmit='ValidateForm();'>
Run Code Online (Sandbox Code Playgroud)

... ... VS

<input type='submit' value='Click Me' onSubmit='return ValidateForm();'>
Run Code Online (Sandbox Code Playgroud)

在第二个实例中,如果ValidateForm函数返回false,表单将不会提交,在第一个即使函数返回false,表单仍将提交.

我认为这种情况下,您可以看到使用return关键字之间的不同而不是.

更新为了简化,如果使用return关键字,则将值传递回调用的函数onsubmit.没有它,您只需调用您在事件处理程序中命名的函数并且不返回任何内容.

  • @overexchange测试它,看看会发生什么.:-) (2认同)

Y. *_*ham 38

从函数返回false将中止检查的效果.因为编写硬编码到html属性的函数的本机(它变成了一些新的本地函数),编写没有单词"return"的html将只运行该函数,并丢失其返回值,就好像你写了:

function doAlert() {
   if(some_condition)
     return false;
   else
     return true;
}
function some_local_function() {
   doAlert();
}
Run Code Online (Sandbox Code Playgroud)

函数some_local_function不会返回任何值,尽管doAlert返回.

当你写"return"时,就像你写了第二个函数:

function some_local_function() {
   return doAlert();
}
Run Code Online (Sandbox Code Playgroud)

它保留了doAlert的返回值,无论它是什么.如果是真的 - 将执行操作(将选中复选框) - 否则 - 它将取消.

你可以在这里看到实时expamle:http://jsfiddle.net/RaBfM/1/