0

这是我创建注册页面的尝试,但是在 for 循环之后,接下来的任何内容都不会执行,我不知道为什么?下面是javascript代码和表格

<script type='text/javascript'>
myArray = ['username','email','password','password2'];
reply = ['User Name','Email','Password','Password Again'];
message = "Please Type you're ";
start = "<font color = red size='-1'>";
end = "</font>";
test = 10;
obj = validate();
alert (obj);
function validate(){

for (var i=0; i<=myArray.length; i++) {
               if (document.getElementById("in"+myArray[i]).value == "")
               {
                   document.getElementById(myArray[i]).innerHTML = start+message+reply[i]+end;
                   test = 30;
               }
                }
alert ("test");
}

<form action="echo.php" method="post" name="register" onsubmit="return validate();">
<table>
    <tr>
      <td width="185"><font size="2">First Name</font></td>
      <td width="499">
        <input id = "infirst_name" name="first_name" type="text" /><div id="first_name"></div></td>
    </tr>
    <tr>
      <td><font size="2">Last Name</font></td>
      <td><input id = "inlast_name" name="last_name" type="text" /><div id="last_name"></font></div></td>
    </tr>
    <tr>
      <td><font size="2">Username*</font></td>
      <td>
        <input id = "inusername" name="username" type="text" /><div id="username"></div></td>
    </tr>
    <tr>
      <td><font size="2">Email*</font></td>
      <td><input id = "inemail" name="email" type="text" /><div id="email"></div></td>
    </tr>
    <tr>
      <td><font size="2">Password*</font></td>
      <td><input id = "inpassword" name="password" type="password" /><div id="password"></div></td>
    </tr>
    <tr>
      <td><font size="2">Repeat Password*</font></td>
      <td>
        <input id = "inpassword2" name="password2" type="password" /><div id="password2"></div></td>
    </tr>
    <tr>
    <tr>
      <td><font size="2">I have read and Agree to the Terms and Conditions</font></td>
      <td>
        <input id = "incheckme" name="checkme" type="checkbox" /><div id="checkme"></div></td>
    </tr>
    <tr>
      <td><input type="submit" value="Register" /></td>
      <td>&nbsp;</td>
    </tr>
  </table>
</form>
4

3 回答 3

6

尝试修复你的循环:

for (var i=0; i < myArray.length; i++) {

如果遇到未捕获的错误,JavaScript 将停止执行任何操作。在您的情况下,您似乎已经遍历了最后一个元素(并试图在未定义的对象上设置 innerHTML)。

于 2012-04-10T11:18:12.007 回答
2

很可能是因为您遍历数组的末尾,但引用它就像那里有东西一样。

于 2012-04-10T11:18:03.083 回答
1

请参阅 JS 控制台输出:也许它说您有错误。 i超出myArray长度:将循环条件从“i<=”更改为“i<”,你会没事的。

于 2012-04-10T11:18:52.393 回答