简体   繁体   English

在 onclick 事件上触发 2 个函数

[英]trigger 2 functions on an onclick event

I am calling 2 functions on an onclick event of a button, first function to check the form validations and the next one for hiding the form if and only if the validation is true.我在按钮的 onclick 事件上调用 2 个函数,第一个 function 用于检查表单验证,下一个用于在验证为真时隐藏表单。 But the problem here is when i click the Button both the functions are been simultaneously called and eventhough validation is false form gets hided quickly.但是这里的问题是,当我单击按钮时,这两个函数都被同时调用,即使验证是错误的,表单也会很快被隐藏。 Any solution to this would be helpful.对此的任何解决方案都会有所帮助。 THANKS谢谢

       <p><input type="button" name="send" value="Hide Entries" onclick="validate(),hide();"></p>

call the hide function with in the validate functionvalidate function 中调用hide function

function validate()
{
   //other validation code
   hide();
}

both the functions are been simultaneously called两个函数同时被调用

No, they're not, JavaScript on browsers is single-threaded (barring the use of web workers ).不,他们不是,浏览器上的 JavaScript 是单线程的(除非使用web 工作人员)。 They're being called one after another, because you haven't done anything to tell the interpreter not to run the hide function if validate returns false.它们被一个接一个地调用,因为如果validate返回 false,您没有做任何事情告诉解释器不要运行hide function。

The minimal change would be:最小的变化是:

<p><input type="button" name="send" value="Hide Entries" onclick="if (validate()){hide();}"></p>

...if you want hide to only be called if validate returns a truthy value. ...如果您希望仅在validate返回真实值时才调用hide


Off-topic (slightly): The larger change would be to move the JavaScript logic out of the HTML markup and into a proper script.题外话(稍微):更大的变化是将 JavaScript 逻辑从 HTML 标记中移出并放入适当的脚本中。 Recommend reading up on unobtrusive JavaScript .建议阅读不引人注目的 JavaScript But the above should work with your current structure.但是以上内容应该适用于您当前的结构。

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

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