gpt4 book ai didi

javascript - 检查 JavaScript 中的输入是否为空失败

转载 作者:行者123 更新时间:2023-11-28 14:10:11 24 4
gpt4 key购买 nike

无论是在我输入字符串的情况下还是在我将输入框留空的情况下,我都会得到 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/

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