首页 > 解决方案 > 单击按钮添加“未定义”而不是项目

问题描述

我只想将我的项目添加到列表中。

我试过把"constant value"而不是candidate.value; 然后显示该值。

<div class="card-body">
  <ul id="dynamic-list"></ul>
  <input type="text" id="candidate" />
  <button onclick="addItem()">add item</button>
  <button onclick="removeItem()">remove item</button>
  <script type="text/javascript">
    function addItem() {
      var ul = document.getElementById("dynamic-list");
      var candidate = document.getElementById("candidate");
      var li = document.createElement("li");

      li.setAttribute('id', candidate.value);
      li.appendChild(document.createTextNode(candidate.value));
      ul.appendChild(li);
    }

    function removeItem() {
      var ul = document.getElementById("dynamic-list");
      var candidate = document.getElementById("candidate");
      var item = document.getElementById(candidate.value);

      ul.removeChild(item);
    }
  </script>
</div>

该项目应通过单击“添加项目”按钮添加,但它被添加为undefined.

这是 IDE 的屏幕截图:

标签: javascripthtml

解决方案


推荐阅读