无论是在我输入字符串的情况下还是在我将输入框留空的情况下,我都会得到 console.log("Something's error!"); 我的 fieldObj 的 console.log 在这两种情况下都显示为空。
我尝试检查输入字段的内容是否为空:
代码:
let fieldObj = document.getElementById("newListItem").value;
let button = document.getElementById("addItem");
button.addEventListener("click", function() {
if (fieldObj != "") {
console.log(fieldObj);
console.log("Everything ok!");
} else {
console.log(fieldObj);
console.log("Something's wrong!");
}
}, false);
<input id="newListItem" type="text" />
<button id="addItem">Add</button>
如果有任何帮助,我将不胜感激!
最佳答案
这是因为您在页面加载后就设置了 fieldObj
,因此它将被设置为 ""
并且永远不会更改。
您需要更新点击监听器内的值:
const button = document.getElementById("addItem");
button.addEventListener("click", function() {
const fieldObj = document.getElementById("newListItem").value;
if (fieldObj !== "") {
console.log(fieldObj);
console.log("Everything ok!");
} else {
console.log(fieldObj);
console.log("Something's wrong!");
}
}, false);
<input id="newListItem" type="text" />
<button id="addItem">Add</button>
关于javascript - 检查 JavaScript 中的输入是否为空失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59861886/