Javascript - 单击时需要删除 li 元素

Javascript - Need to remove li element when clicked

本文关键字:删除 li 元素 单击 Javascript      更新时间:2023-09-26

我需要一些帮助来完成我正在处理的作业。 使用 JavaScript,我需要在我的 removeItem() 函数中使用 .target 事件属性,以便在单击它们时删除 li 元素。谁能帮忙? 我的代码如下。

  function Post(item) {
      this.item = item;
      this.print = function() {
          var s = this.item;
          return s;
      }
  }
  var postList = [];
  window.onload = init;
  function init() {
      var submitButton = document.getElementById("submitButton");
      submitButton.onclick = getAddedItem;
  }
  function getAddedItem() {
      var itemInput = document.getElementById("item");
      var item = itemInput.value;
      if (item == null || item == "") {
          alert("Please enter an item");
          return;
      } else {
          var post = new Post(item);
          postList.push(post);
          addPostToList(post);
          var theForm = document.querySelector("form");
          theForm.reset();
      }
      function addPostToList(post) {
          var postList = document.querySelector("ul");
          var li = document.createElement("li");
          li.onclick = removeItem(li);
          postList.appendChild(li);
          li.innerHTML = post.print();
      }
  };
  function removeItem(li) {
      var test = document.getElementsByTagName("li");
      for (i = 0; i < test.length; i++) {
          test[i].onclick = function() {
              var test = document.querySelector("li");
              if (test) {
                  var testParent = test.parentElement;
                  testParent.removeChild(test);
              }
          }
      }
}  
p {
    font-style:italic
}
li:hover {
    cursor:pointer
}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>
    </title>
    <meta charset="utf-8">
</head>
<body>
    <form>
        <label for="item">Add an item:</label> <input id="item" size="20" type="text"><br>
        <input id="submitButton" type="button" value="Add!">
    </form>
    <ul>
    </ul>
    <p>Click an item to remove it from the list.</p>
</body>
</html>

以下是要更改的代码部分(请参阅注释):

function addPostToList(post) {
    var postList = document.querySelector("ul");
    var li = document.createElement("li");
    //Don't apply removeItem here. Just give the function name
    //The event will be passed to removeItem
    li.onclick = removeItem;
    postList.appendChild(li);
    li.innerHTML = post.print();
}

function removeItem(e) {    
    e.target.parentElement.removeChild(e.target);
}

这是一个完整的JSBin:http://jsbin.com/mivonanoga/1/