每次用户按下“添加”按钮之前我都需要检查是否输入了数据,但是我的“if...else” block 在它开始接受数组中的空白条目之后只工作一次。我不确定为什么下次会失败。任何帮助都是可观的,因为我是 java 脚本的新手。 这是我的代码片段。
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Click the button to add a new el</title>
</head>
<body>
<label>Enter an New item to add in Stock</label>
<br>
<input type="text" name=" itemName" id="addItemInStock"></input>
<br>
<p id="errorMsg"></p>
<button onclick="addToStock()">Add</button>
<p id="showList"></p>
<p id="listCount"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("showList").innerHTML = fruits;
var newItem = document.getElementById("addItemInStock");
function addToStock() {
if ((newItem.value) === "") {
document.getElementById("errorMsg").innerHTML = "Blank item cannot be added!!";
} else {
document.getElementById("errorMsg").style.display = "none";
fruits.push(newItem.value);
document.getElementById("showList").innerHTML = fruits;
clearAndShow();
}
}
function clearAndShow() {
newItem.value = " ";
}
</script>
</body>
</html>
最佳答案
您的 clearAndShow
函数将输入元素值设置为单个空格,但 if
检查空字符串。
您还在第一次显示时将 display
设置为 none,但永远不要将其切换回 block
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("showList").innerHTML = fruits;
var newItem = document.getElementById("addItemInStock");
function addToStock() {
if ((newItem.value) === "") {
document.getElementById("errorMsg").innerHTML = "Blank item cannot be added!!";
document.getElementById("errorMsg").style.display = "block";
} else {
document.getElementById("errorMsg").style.display = "none";
fruits.push(newItem.value);
document.getElementById("showList").innerHTML = fruits;
clearAndShow();
}
}
function clearAndShow() {
newItem.value = "";
}
<label>Enter an New item to add in Stock</label>
<br>
</br>
<input type="text" name=" itemName" id="addItemInStock"></input>
<br></br>
<p id="errorMsg"></p>
<button onclick="addToStock()">Add</button>
<p id="showList"></p>
<p id="listCount"></p>
关于javascript - 为什么 if..else block 只能工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40611835/