gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'parentElement' of undefined on . 删除()

转载 作者:行者123 更新时间:2023-11-28 03:24:00 25 4
gpt4 key购买 nike

我正在使用此函数动态创建按钮

function addFormFields() {
i += 1
const parentdiv = document.createElement('div')
const delicon = document.createElement('i')
const btndelete = document.createElement('button')
const div = document.createElement('div')
const container = document.getElementById('compinput')
const selectprod = document.createElement('select')
const inputqtd = document.createElement('input')
delicon.setAttribute("class", "fas fa-trash-alt")
btndelete.setAttribute("class", "btn btn-danger btn-sm")
btndelete.setAttribute("type", "button")
btndelete.setAttribute("onclick", "deletebtn()")
div.setAttribute("class", "row justify-content-between col-md-12")

inputqtd.setAttribute("class", "form-control col-md-4 mt-1")
inputqtd.setAttribute("min", "0")
inputqtd.setAttribute("max", "999")
inputqtd.type = "number"
inputqtd.name = "qtd[]"
inputqtd.placeholder = " Quantidade"



selectprod.setAttribute("class", "form-control col-md-6")
selectprod.type = "text"
selectprod.name = "prod[]"
selectprod.placeholder = "Produtos que compoem"


console.log(lista_prod)

for (let i = 0; i < lista_prod.length; i++) {
const opt = document.createElement('option');
opt.value = lista_prod[i];
opt.innerHTML = lista_prodname[i]
selectprod.appendChild(opt)

}

btndelete.appendChild(delicon)
div.appendChild(selectprod)
div.appendChild(btndelete)
parentdiv.appendChild(div)
parentdiv.appendChild(inputqtd)
container.appendChild(parentdiv)

container.appendChild(document.createElement("br"))
}

并向该按钮添加一个名为deletebtn的onlick函数,如下所示:

function deletebtn(e) {
e.parentElement.remove();
}

应该发生什么:删除按钮btndelete应该onclick删除他动态创建的parentElement,它被称为parentdiv,但是当我尝试删除时,我收到了类似于问题标题的错误,因此它不将动态创建的 div 视为他的parentElement,我该如何执行该操作?

最佳答案

您已在同一范围内拥有parentdiv 和删除按钮。为什么不添加这样的事件处理程序:

btndelete.addEventListener("click",() => {
container.removeChild(parentdiv);
});

关于javascript - 类型错误 : Cannot read property 'parentElement' of undefined on . 删除(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58837982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com