简体   繁体   English

Javascript:删除父元素

[英]Javascript :delete a parent element

How can I delete the parent element of a child using an event listener.如何使用事件侦听器删除子元素的父元素。

I have an html form that when submitted, runs the makeNewBook function and pushes an object containing the form information to an array called myLibrary.我有一个 html 表单,提交时运行 makeNewBook function 并将包含表单信息的 object 推送到名为 myLibrary 的数组。 It then creates a container div that displays the info from that form, which is placed in a predefined div called shelf(bookshelf).然后它创建一个容器 div,显示来自该表单的信息,该表单放置在一个名为shelf(bookshelf) 的预定义div 中。 That container also has a delete button in it.该容器中还有一个删除按钮。

The delete button has an event listener that removes the object from the array, but how can I also remove the container from the page using that last event listener?删除按钮有一个事件侦听器,可以从数组中删除 object,但是我怎样才能使用最后一个事件侦听器从页面中删除容器? Thanks谢谢

Javasctipt: 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
    })

}

You have to call remove on the node itself您必须在节点本身上调用remove

deleteBtn.parentElement.remove();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM