gpt4 book ai didi

javascript - innerHTML 适用于 body 元素,但不适用于 p 元素

转载 作者:行者123 更新时间:2023-11-28 20:31:46 26 4
gpt4 key购买 nike

如果电子邮件地址无效,我想在屏幕上显示一条消息“请输入有效的电子邮件地址”。 body 元素的innerHTML 语句工作正常,但我用于p 元素的innerHTML 语句不起作用。

有一次,当我测试它时,我看到显示“请输入有效的电子邮件地址”消息,然后在我单击“无效”警报框的“确定”按钮后,该消息消失了。

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>

最佳答案

无论如何,表单都会提交,因为您没有阻止默认操作。这就是消息出现(工作)和消失(页面重新加载)的原因

function validateEmail(e) {
if( valid ) { /* stuff */ }
else {
e.preventDefault(); // Prevent form submission
/* etc */

关于javascript - innerHTML 适用于 body 元素,但不适用于 p 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16218223/

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