如果电子邮件地址无效,我想在屏幕上显示一条消息“请输入有效的电子邮件地址”。body 元素的 innerHTML 语句工作正常,但我用于 p 元素的语句不起作用。
有一次我在测试它时,看到消息“请输入一个有效的电子邮件地址”显示,然后在我单击“无效”警告框的确定按钮后,该消息消失了。
JavaScript:
<script type="text/javascript">
function validateEmail() {
var emailRule = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (emailRule.test(document.forms[0].email.value)) {
document.getElementById("body").innerHTML = "Thank you for signing up for our newsletter! You will recieve a confirmation email shortly.";
setTimeout("window.close()", 3000);
}
else
window.alert("not valid"); //for debugging
document.getElementById("message").innerHTML = "Please enter a valid email address";
}
</script>
HTML:
</head>
<body id="body">
<p>If you sign up for our newsletter you will be entered into a drawing to win free clothes every month!</p>
<br>
<p id="message"> </p>
<form action="" onsubmit="validateEmail();">
<p>Email: <input type="text" name="email"/>
<input type="submit" value="Sign up"/></p>
<br>
<input type="button" value="No thanks" onclick="window.close()"/>
<br>
</form>
<p><a href="privacy.html">Privacy Policy</a></p>
</body>
</html>