首页 > 解决方案 > 如何通过单击放置在其中的按钮来删除整个列表项?

问题描述

我正在制作一个待办事项列表应用程序。我想通过单击附加到列表元素的按钮来删除项目,但它只删除按钮而不是整个元素。目前,<li>a 中的元素<ul>如下:

function newElement() {
    event.preventDefault(); // stop default redirect

    var li = document.createElement("li"); // create an <li> element

    /* make a text node from the input and put it in the <li> */
    var inputValue = document.getElementById("task").value; // retrieve value of text box
    var t = document.createTextNode(inputValue); // create a text node of the box value
    li.appendChild(t); // put the text node in the single <li>

    /* attach a button to the <li> element that deletes it */
    var btn = document.createElement("BUTTON"); // Create a <button> element
    btn.innerHTML = "X"; // Insert text
    btn.className = "button" // add class name for CSS targeting
    btn.addEventListener('click', removeItem); // add event listener for item deletion

    li.appendChild(btn); // Append <button> to <li> 

    li.addEventListener('click', checkToggle); // add event listener for a click to toggle a strikethrough

    appendItem("list", li); //append the li item to the ul
}

按钮的侦听器调用的函数显示为:

function removeItem() {
    this.parentNode.removeChild(this);
}

我希望按钮删除整个<li>节点,但它只删除它的按钮部分。

标签: javascripthtml

解决方案


只需将这一步向上移动

function removeItem() {
    this.parentNode.parentNode.removeChild(this.parentNode);
}

推荐阅读