-1

这是我的代码

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <script type = "text/javascript">
          function validate(){
              var warnings = "some warnings";               
              document.getElementById("alert").innerHTML = warnings;
              document.getElementById("alert").styledisplay = "block";
              return true;
          }
        </script>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
      </head>
      <body>
        <div id = "alert"></div>
        <div id = wrapper>
          <h2>Enter Your Info</h2>
          <form name = "myForm" onSubmit = "javascript:validate()">
        <div>
          <label for = "username">User Name:</label>
          <input type = "text" name = "username" id = "username"/>
        </div>
        <div>
          <label for = "firstname">First Name:</label>
          <input type = "text" name = "firstname" id = "firstname"/>
        </div>
        <div>
          <label for = "lastname">Last Name:</label>
          <input type = "text" name = "lastname" id = "lastname"/>
        </div>
        <div>
          <label for = "password">Password:</label>
          <input type = "password" name = "password" id = "password"/>
         </div>
        <div>
          <input type = "submit" value = "submit" id = "submit"/>
        </div>
          </form>
        </div>
      </body>
    </html>

我遇到的问题是当我单击提交按钮时没有任何反应。不知道为什么,我对 java 脚本和 html 很陌生,但是我读过的所有内容都说这应该可以工作,任何帮助将不胜感激。

4

1 回答 1

2

你总是回来true。所以表单将提交。而是试试这个:

<form name="myForm" onSubmit="return validate()">

 function validate() {

     var warnings  = validate();

     document.getElementById("alert").innerHTML = warnings;
     document.getElementById("alert").styledisplay = "block";
     if(warnings) return false; //If any warning i don't want to submit.
     return true;
 }

只是为了补充。if(warnings)将根据您设置的初始警告状态使条件失败,或者从您的验证函数中不对其进行任何设置(在验证成功的情况下)返回空字符串或返回 null、未定义等或不返回任何内容...

于 2013-09-20T22:43:57.670 回答