为什么这个 Javascript 函数不显示 alert()?

Why isn't this Javascript function showing the alert()?

我有一个功能可以在两个元素未填写时显示警报,但警报没有显示,它只是重新加载页面。不确定我错过了什么或哪里出错了。 这是 Javascript:

function submitNewsletter() {
    var name = document.getElementById("name");
    var email = document.getElementById("email");
    if (name == "" || email == "") {
        alert("Please fill in your details.");
        return false;
    }
}

这里是 html 是为了:

<section class="signup">
        <h1>Keep up to date.</h1>
        <p>Sign up to our newsletter to hear about improvements and additions to Electric Dreams.</p>
        <form class="newsletterForm">
            <label for="name" class="label">Full Name</label>
            <input type="text" id="name" name="name" class="input" placeholder="Full Name"> <br>
            <label for="email" class="label">Email Address</label>
            <input type="email" id="email" name="email" class="inout" placeholder="Email Address"> <br>
            <button type="submit" class="btn" onclick="submitNewsletter()">Submit</button>
        </form>
    </section>

此代码不起作用的原因有几个。

  1. 您还没有在表单上设置事件侦听器
  2. 您正在检查变量 nameemail 是否为空字符串,而不是检查 name.valueemail.value 是否为空字符串。 nameemail 是 HTML 元素,要检查它们的值,您必须检查 .value
  3. 您没有检查每个的 .value 是否为 null
  4. 您必须在表单的提交回调函数中调用 event.preventDefault()。否则表单的提交将导致页面重新加载。

这里是修改后的代码:

function submitNewsletter(event) {
    event.preventDefault();
    var name = document.getElementById("name");
    var email = document.getElementById("email");
    if (name.value === "" || email.value === "" || !name.value || !email.value) {
        alert("Please fill in your details.");
        return false;
    }
}

document.querySelector(".newsletterForm")
    .addEventListener('submit', submitNewsletter);

JSFiddle:https://jsfiddle.net/qu2pesw0/1/

因为您在 if 语句中检查名称,并通过电子邮件发送 DOM 元素是否存在。您想检查输入元素的值。

function submitNewsletter() {
    var name = document.getElementById("name");
    var email = document.getElementById("email");
    if (name.value == "" || email.value == "") {
        alert("Please fill in your details.");
        return false;
    }
}
<section class="signup">
    <h1>Keep up to date.</h1>
    <p>Sign up to our newsletter to hear about improvements and additions to Electric Dreams.</p>
    <form class="newsletterForm">
        <label for="name" class="label">Full Name</label>
        <input type="text" id="name" name="name" class="input" placeholder="Full Name"> <br>
        <label for="email" class="label">Email Address</label>
        <input type="email" id="email" name="email" class="inout" placeholder="Email Address"> <br>
        <button type="submit" class="btn" onclick="submitNewsletter()">Submit</button>
    </form>
</section>

希望你一切都好

这是您首先应该如何获取价值输入

function submitNewsletter() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (name == "" || email == "") {
    alert("Please fill in your details.");
    return false;
}

}