这是我创建注册页面的尝试,但是在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> </td>
</tr>
</table>
</form>
答案 0 :(得分:5)
尝试修复循环:
for (var i=0; i < myArray.length; i++) {
如果遇到未捕获的错误,JavaScript将停止执行任何操作。在你的情况下,似乎你已经循环了最后一个元素(并尝试在未定义的对象上设置innerHTML)。
答案 1 :(得分:2)
最有可能的原因是你遍历数组的末尾,但引用它就像那里有东西一样。
答案 2 :(得分:1)
请参阅JS控制台输出:也许它说您有错误。
i
超出myArray
长度:将循环条件从“i&lt; =”更改为“i&lt;”你会没事的。