简体   繁体   English

JavaScript函数之间的区别

[英]Difference between JavaScript Function

I have some doubt in my mind that if a jsp page onclick() calls a JavaScript method. 我有一些疑问,如果一个jsp页面onclick()调用一个JavaScript方法。

I have two scenarios 我有两个场景

  1. onclick="return validatePage();"
  2. onclick="validatePage();"

What is the difference between these two types calling of JavaScript methods. 这两种类型调用JavaScript方法有什么区别。

On the first, by returning the return value of the function, you will cancel the default action for the event when the function returns false . 首先,通过返回函数的返回值,当函数返回false时,将取消事件的默认操作。 Similar to calling event.preventDefault() . 与调用event.preventDefault()类似。 It is notably used when checking for forms validity, where returning false will cancel the form submission. 它在检查表单有效性时特别使用,返回false将取消表单提交。

ps. PS。 In the case of form validation, instead of binding the validation function a button's onclick , you should attach it to the form's onsubmit event. 在表单验证的情况下,您应该将它附加到表单的onsubmit事件,而不是将验证函数绑定到按钮的onclick This way if the user triggers the submit through pressing Enter on an input, the form will still be checked before submitting. 这样,如果用户通过在输入上按Enter键来触发提交,则在提交之前仍将检查表单。

If you return false from the javascript function , onclick = "return validatePage();" 如果从javascript函数返回false,则onclick =“return validatePage();” wont submit the form values. 不会提交表单值。

where as, in the case of onclick = "validatePage();" 其中,在onclick =“validatePage();”的情况下 will submit the form values even if you return false from the Javascript function. 即使您从Javascript函数返回false,也会提交表单值。

For an onclick event those two scenarios are essentially equivalent. 对于onclick事件,这两个场景基本上是等效的。 The reason you would use "return" is more closely related to an onsubmit event of a form instead of onclick. 您使用“return”的原因与表单的onsubmit事件而不是onclick更密切相关。 When you use it with onsubmit, if the function returns false it will prevent the form from being submitted. 与onsubmit一起使用时,如果函数返回false,则会阻止提交表单。

Number 1 will return the value, returned by the validatePage(); Number 1将返回由validatePage();返回的值validatePage(); function. 功能。 This can be used to interrupt key presses, for example (returning false on the onkeyup of a input field), or to use a anchor ( <a href=".... ) as a JavaScript button. Number 2 will simply execute the function. 这可用于中断按键,例如(在输入字段的onkeyup上返回false ),或使用锚点( <a href=".... )作为JavaScript按钮。数字2将只执行功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM