按钮单击 Javascript 后显示错误

H. *_*lyn 1 html javascript button buttonclick

单击按钮后,我会检查我的文本字段是否不为空。我的支票有效,但如果我显示我的消息,它会显示几秒钟。可能是我点击按钮的持续时间。这是我尝试过的一些代码。

<form>
    <div id="errorblock">
        <p id="errortext">Error.</p>
    </div>
    <!-- here are my input fields-->

    <button>Send</button>
</form>
Run Code Online (Sandbox Code Playgroud)

这是我在页面初始化后添加事件侦听器的地方:

document.getElementsByTagName("button")[0].addEventListener("click", function(){
    sendEmail();
});

function sendEmail() {

    //check if all fields are fill in. If not do this code;
    document.getElementById("errortext").innerHTML = "Fill in all the fields please.";

    var errorblock = document.getElementById("errorblock");       
    errorblock.style.visibility = "visible";
    errorblock.style.height = "46px";
}
Run Code Online (Sandbox Code Playgroud)

谁能帮我?谢谢

dfs*_*fsq 5

默认情况下HTMLButtonElement具有type="submit". 这意味着在按钮单击时提交表单。您需要确保在表单中出现错误的情况下阻止此提交。例如通过调用preventDefault事件对象的方法:

document.getElementsByTagName("button")[0].addEventListener("click", function (e) {
    if (!sendEmail()) {
        e.preventDefault();
    }
});

function sendEmail() {

    //check if all fields are fill in. If not do this code;
    document.getElementById("errortext").innerHTML = "Fill in all the fields please.";

    var errorblock = document.getElementById("errorblock");
    errorblock.style.visibility = "visible";
    errorblock.style.height = "46px";

    // if there are errors return false
    // return true if input is correct
    return false;
}
Run Code Online (Sandbox Code Playgroud)

另外我建议onsubmit在表单上监听事件而不是按钮点击事件:

document.querySelector("form").addEventListener("submit", function (e) {
    if (!sendEmail()) {
        e.preventDefault();
    }
});
Run Code Online (Sandbox Code Playgroud)