[英]Javascript :delete a parent element
如何使用事件侦听器删除子元素的父元素。
我有一个 html 表单,提交时运行 makeNewBook function 并将包含表单信息的 object 推送到名为 myLibrary 的数组。 然后它创建一个容器 div,显示来自该表单的信息,该表单放置在一个名为shelf(bookshelf) 的预定义div 中。 该容器中还有一个删除按钮。
删除按钮有一个事件侦听器,可以从数组中删除 object,但是我怎样才能使用最后一个事件侦听器从页面中删除容器? 谢谢
Java脚本:
function makeNewBook() {
let x = new Book(bookInput.value, authorInput.value, pagesInput.value, readInput.value) //create a new book using the input vals
myLibrary.push(x) //push the new book object to the books array;
console.table(myLibrary)
let container = document.createElement('div') //create a container for all the info
container.setAttribute('class', 'container')
let titlePara = document.createElement('p')
titlePara.textContent += 'Title: ' + x.title;
let authorPara = document.createElement('p')
authorPara.textContent += 'Author: ' + x.author;
let pagesPara = document.createElement('p')
pagesPara.textContent += 'Pages: ' + x.pages;
let readPara = document.createElement('p')
readPara.textContent += 'Read: ' + x.read
// delete button
let deleteBtn = document.createElement('input');
deleteBtn.setAttribute('class','delete')
deleteBtn.type = 'submit';
deleteBtn.value = 'Delete'
// append everyhting to the container div to be put on the shelf
container.appendChild(titlePara)
container.appendChild(authorPara)
container.appendChild(pagesPara)
container.appendChild(readPara)
container.appendChild(deleteBtn)
container.setAttribute('class', `container ${x.title}`)
shelf.append(container)
deleteBtn.addEventListener('click',()=>{
let index= myLibrary.indexOf(x);
myLibrary.splice(index,1); //delete that object from the myLibrary array
document.body.remove(deleteBtn.parentElement) //This does not work
})
}
您必须在节点本身上调用remove
deleteBtn.parentElement.remove();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.