gpt4 book ai didi

javascript - 验证表单时出现 "null or not an object"错误

转载 作者:行者123 更新时间:2023-12-02 18:47:27 25 4
gpt4 key购买 nike

我正在使用这个:

<script type="text/javascript">
var emailRule = /^[_\w\-]+(\.[\w\-]+)*(\.[\D]{2,3})$/;

if (emailRule.test(document.forms[0].email.value))
window.alert("That was a valid email address");
else
window.alert("That was not a valid email address");
</script>

验证这一点:

<form action="">
<p>Email: <input type="text" name="email"/>
<input type="submit" value="Sign up"/></p>
<br>
</form>

该表单是页面上唯一的表单,并且该输入框是页面上唯一的表单元素。我收到此错误:

document.forms.0.email is null or not an object

我也尝试将其更改为 document.forms[0].elements[0].value 但出现相同类型的错误。

最佳答案

因为您在页面呈现时调用它,所以该元素尚不存在。

您需要将该代码封装在名为 onsubmit 的验证函数中。

关于javascript - 验证表单时出现 "null or not an object"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16216483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com