使框出现的按钮:
<button onclick="create()">create box</button>
<div id="trades"></div>
该框出现的位置:
<div class="box" id="duplicater">
</div>
创建盒子的函数:
function create() {
var box = document.createElement("div");
box.setAttribute('class', 'itembox')
//delete button to remove the box
var remove = document.createElement("span");
remove.setAttribute('class', 'remove');
remove.setAttribute('id', 'Remove')
remove.innerText = "x";
box.appendChild(remove);
var holder = document.createElement("p");
holder.setAttribute('class', 'output');
holder.innerText = "The text in the box"
box.appendChild(holder);
var trades = document.getElementById("trades");
trades.appendChild(box);
}
按下删除按钮时删除该框:
var removeItem = document.getElementById("Remove")[0];
removeItem.onclick = function() {
trades.removeChild(box)
}
最佳答案
如果我正确理解你的问题,那么这可以通过调用要删除的框元素上的 remove()
方法来实现。添加此代码:
remove.onclick = function() {
box.remove();
}
在 create()
函数中定义 remove
元素的位置,如下所示:
function create() {
var box = document.createElement("div");
box.setAttribute('class', 'itembox')
//delete button to remove the box
var remove = document.createElement("span");
remove.setAttribute('class', 'remove');
remove.setAttribute('id', 'Remove')
remove.innerText = "x";
box.appendChild(remove);
// define onclick behavior for remove element
// and call 'remove()' on the box element to
// delete it as required
remove.onclick = function() {
box.remove();
}
var holder = document.createElement("p");
holder.setAttribute('class', 'output');
holder.innerText = "The text in the box"
box.appendChild(holder);
var trades = document.getElementById("trades");
trades.appendChild(box);
}
<button onclick="create()">create box</button>
<div id="trades"></div>
作为补充说明,将事件绑定(bind)到 DOM 的首选方法是通过 addEventListener()
,而不是将处理函数分配给 onclick
等事件。要在代码中使用 addEventListener()
,您可以重写:
remove.onclick = function() {
box.remove();
}
如:
remove.addEventListener('click', function() {
box.remove();
})
关于javascript - 如何使用已创建的元素删除已创建的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53658360/