所以我有一个显示错误消息的计算器,如果他们在输入为 NaN 的情况下按下“计算”按钮。每次用户按下计算时,都会不断创建错误消息。我如何才能让它即使在多次按下“计算”后也只显示?
function displayErr() {
const formBox = document.querySelector("form");
const errorBox = document.createElement("div");
errorBox.className = "errorBox";
const errorText = document.createTextNode("Those are not numbers!");
errorBox.appendChild(errorText);
formBox.appendChild(errorBox);
}
if ((isNaN(billInput)) || (isNaN(peopleAmount)) || (billInput === "") || (peopleAmount === "")) {
displayErr();
}
最佳答案
最直接的方法是check if the element already exists.
function displayErr() {
// Get error element
const errorElement = document.getElementsByClassName('errorBox');
// If it already exists
if (errorElement && errorElement.length > 0) {
// Dont add another one
return;
}
// Add new errorBox
const formBox = document.querySelector("form");
const errorBox = document.createElement("div");
errorBox.className = "errorBox";
const errorText = document.createTextNode("Those are not numbers!");
errorBox.appendChild(errorText);
formBox.appendChild(errorBox);
}
另一种选择是使用 css 类来“隐藏”元素;
- 始终呈现该元素,但使用
display: none
隐藏它 - 在
displayErr()
中,使用类似document.getElementsByClassName('errorBox')[0].style.display = block;
的方式使元素可见
关于Javascript 只显示一次 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64119168/