javascript - 如何通过单击放置在其中的按钮来删除整个列表项?
问题描述
我正在制作一个待办事项列表应用程序。我想通过单击附加到列表元素的按钮来删除项目,但它只删除按钮而不是整个元素。目前,<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>
节点,但它只删除它的按钮部分。
解决方案
只需将这一步向上移动
function removeItem() {
this.parentNode.parentNode.removeChild(this.parentNode);
}
推荐阅读
- javascript - 声明接口而不是类型
- vue.js - 将 v-bind 添加到属性时 v-dialog 的 v-btn 消失
- c# - 我们如何在 PDFLib set-graphics-option 中传递专色值列表?
- javascript - 使用 map() 从另一个数组元素值更改数组元素顺序
- node.js - 使用 npm 和 Zurb Foundation 安装 Swup 的问题
- python - 使用 Beautiful Soup 4 提取带有连字符的属性值
- ruby - 创建带索引的数组,并与其他数组进行比较
- mount - 如何在 Linux 中挂载非超级用户可以写入的驱动器
- arrays - ColdFusion 中的类型化数组与非类型化数组
- c++ - 如何知道项目中包含最多的文件?