繁体   English   中英

验证表单时,Javascript函数运行两次

[英]Javascript function runs twice when validating form

我敢肯定对此有一个简单的解释。 每当尝试选择“未选中”(我相信默认情况下选中)选项时,我都会尝试提醒我“必须选择国家”,然后单击“ 验证”按钮 我已经能够获得正确显示警报的功能,但是问题是警报显示了两次。

为什么警报会显示两次,我如何才能只显示一次? 谢谢!

 function CountrySelectValidation() { // ensures country is selected var ValidateCountry = document.forms["registration-form"]["Country"].value; if (ValidateCountry == "not-selected") { alert("Country must be selected"); return false; } else { return true; } } function SubmitForm() { if (CountrySelectValidation()) { // check if true, then execute this code document.getElementById("registration-form").submit(); } } 
 <form id="registration-form"> What country are you from? <select name="Country"> <option value="not-selected">Not Selected</option> <option value="england">England</option> <option value="wales">Wales</option> <option value="scotland">Scotland</option> <option value="northern-ireland">Northern Ireland</option> </select> <br><br><input type="submit" value="Submit Method 1"> <button type="reset">Reset Method 1</button> <button type="submit" id="submit-2">Submit Method 2</button> </form> <button onClick="ResetForm()">Reset Method 1</button> <button onClick="CountrySelectValidation(); SubmitForm()">Validation</button> 

CountrySelectValidation()
...
if (CountrySelectValidation())

您在if (实际上执行)中运行CountrySelectValidation函数,因此这就是它运行两次的原因。

当您调用if语句时,您将再次执行该函数。 从if语句中的代码在原始函数内部另一个不同的函数中运行。

OriginalFunction () {

      //Content here

      FunctionToHandleIfstatement();

 }

暂无
暂无

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

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