Javascript:如何删除元素绑定删除按钮(动态)

时间:2016-03-05 04:48:39

标签: javascript

我目前正在使用添加按钮将文本框中的输入添加到列表中。我还绑定了每个列表元素的按钮,然后将它们附加到无序列表。如何删除相应删除按钮的元素?仅限纯JavaScript。

window.onload = function() {

  var elements = [];
  var textInput;

  document.getElementById("addButton").onclick = function() {

    textInput = document.getElementById("inputBox").value;

    if (textInput == "") {
      alert("Make sure your input is not empty!");
    } else {


      var liNode = document.createElement('li');
      var btnNode = document.createElement('button');

      var btnText = document.createTextNode("Remove Item");
      btnNode.appendChild(btnText);

      var textNode = document.createTextNode(textInput);
      liNode.appendChild(textNode);
      liNode.appendChild(btnNode);

      document.getElementById("myInputList").appendChild(liNode);
    }

  }


  function addElementToList(element) {
    if (element != "") {
      elements.push(element);
    } else {
      alert("Make sure the input field is not empty!")
    }
  }
}
<!DOCTYPE html>
<html>

<body>

  <head>
    <script src="func.js"></script>
  </head>

  <input type="text" id="inputBox">
  <br>
  <button id="addButton">Add</button>
  <br>
  <br>
  <ul id="myInputList"></ul>

</body>

</html>

1 个答案:

答案 0 :(得分:3)

  

使用addEventListener在创建的按钮上注册click个事件。

使用.remove(),从其所属的树中删除对象。

试试这个:

window.onload = function() {
  var elements = [];
  document.getElementById("addButton").onclick = function() {
    var textInput = document.getElementById("inputBox").value;
    if (textInput == "") {
      alert("Make sure your input is not empty!");
    } else {
      var liNode = document.createElement('li');
      var btnNode = document.createElement('button');
      var btnText = document.createTextNode("Remove Item");
      btnNode.appendChild(btnText);
      var textNode = document.createTextNode(textInput);
      liNode.appendChild(textNode);
      liNode.appendChild(btnNode);
      document.getElementById("myInputList").appendChild(liNode);
      btnNode.addEventListener('click', removeHandler);
    }
  }

  function removeHandler() {
    this.parentNode.remove(); // this will be `button` element and `parentNode` will be `li` element
  }

  function addElementToList(element) {
    if (element != "") {
      elements.push(element);
    } else {
      alert("Make sure the input field is not empty!")
    }
  }
}
<input type="text" id="inputBox">
<br>
<button id="addButton">Add</button>
<br>
<br>
<ul id="myInputList"></ul>