1 回答
TA贡献1793条经验 获得超6个赞
将id分配给您在addSelection()中创建的div
div.id=`selection${id}`;
在按钮 onclick中传递 id
onClick="removeSelection(${id})"
在removeSelection函数中,通过该id获取元素并将其删除。
document.getElementById(`selection${id}`).remove();
运行以下代码段。
var selectionAmmount = 0;
var id=1;
var div;
function addSelection() {
var div = document.createElement('div')
div.innerHTML = `<br><input type="text" placeholder="Name Of selection"><br><input type="number" placeholder="Price per s.y""><input type="button" value="x" onClick="removeSelection(${id})"><br>`;
div.id=`selection${id}`;
document.getElementById("addSelection").appendChild(div);
selectionAmmount++;
id++;
}
function removeSelection(id) {
selectionAmmount--;
document.getElementById(`selection${id}`).remove();
}
<div>
Has a selection: <input type="checkbox" id="selection" checked><br><br>
<selection id="hideSelection">
<input type="text" placeholder="Name Of selection" id="selectionName"><br>
<input type="number" placeholder="Price per s.y" id="selectionPrice"><br>
<selection id="addSelection"></selection>
<input type="button" value="+ selection" onclick="addSelection()"><br><br>
</selection>
添加回答
举报