javascript - 为什么 if..else block 只能工作一次

标签 javascript arrays if-statement

每次用户按下“添加”按钮之前我都需要检查是否输入了数据,但是我的“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/

相关文章:

javascript - 更改按自定义属性排序的对象数组的顺序

javascript - 从数组中删除值并将它们添加到 POST 方法请求中

c - 输入所有数组后,如何在 C 中打印数组的所有元素?

java - 我试图打印这个而不只是为每一行做 println

excel - VBA:计数出现一对值的次数

javascript - 在 JavaScript 中按两个值对数组进行排序

javascript - 在 IE 中打开的窗口不起作用

Java - farkle(贪婪)游戏(骰子和玩家数组,多个类)

objective-c - 数学逻辑替代 if 语句

javascript - 图表 js 标签和分组标签