javascript - 如何使用已创建的元素删除已创建的元素

标签 javascript html

使框出现的按钮:

<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/

相关文章:

javascript - Vue.js - 我该如何解决 [Vue 警告] : Error in render: "TypeError: Cannot read property ' port' of undefined"?

javascript - 如何计算 Javascript 中的 css 规则优先级?

html - 如何在 Google Script 邮件中将 CSS 添加到我的 html?

javascript - 如何在 jquery 中添加多段的 "read more"链接?

html - 我有两个 div,它们的边距都设置为 0,但它们之间有一个空格

javascript - 扩展特定的列标题以包含向上/向下箭头

javascript - 使用正则表达式匹配动态字符串

javascript - 在浏览器中以实际尺寸显示带有毫米尺寸的 SVG

javascript - Owl Carousel - 在导航按钮中间放置一个图像计数器

javascript - 在另一个 js 文件中调用 JavaScript 函数