单击按钮添加“未定义”而不是项目

时间:2019-11-10 20:47:35

标签: javascript html

我只希望将我的商品添加到列表中。

我尝试放置"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的屏幕截图:

0 个答案:

没有答案