[英]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.