javascript 删除 div onclick

标签 javascript html

使用纯 javascript,我需要在单击 span 时删除 li

  • 通过单击删除,我想删除它的 div。

Object.prototype.remove = function(){
    this.parentNode.removeChild(this);
};

var lis = document.querySelectorAll('li');
var button = document.querySelectorAll('span');

for (var i = 0, len = lis.length; i < len; i++) {
    button[i].addEventListener('click', remove, false);
}
<ul>
    <li>List item one<span> remove</span></li>
    <li>List item two<span> remove</span></li>
    <li>List item three<span> remove</span></li>
    <li>List item four<span> remove</span></li>
    <li>List item five<span> remove</span></li>
    <li>List item six<span> remove</span></li>
</ul>

最佳答案

不要污染Object .您不需要在每个对象中都使用此功能。创建一个单独的函数并使用 remove() , 不是 removeChild() .

ChildNode.remove() 方法从它所属的树中移除对象。

但删除并不适用于所有浏览器。这是一项新功能。因此,我建议您使用两种解决方案。

remove()

var remove = function(){
    this.parentNode.remove();
};

var lis = document.querySelectorAll('li');
var button = document.querySelectorAll('span');

for (var i = 0, len = lis.length; i < len; i++) {
    button[i].addEventListener('click', remove, false);
}
<ul>
    <li>List item one<span> remove</span></li>
    <li>List item two<span> remove</span></li>
    <li>List item three<span> remove</span></li>
    <li>List item four<span> remove</span></li>
    <li>List item five<span> remove</span></li>
    <li>List item six<span> remove</span></li>
</ul>

removeChild() .

为什么有 2 个父节点?

因为第一个是 <span> , 但你需要 li

function remove() {
  this.parentNode.parentNode.removeChild(this.parentNode);
}

var lis = document.querySelectorAll('li');
var button = document.querySelectorAll('span');

for (var i = 0, len = lis.length; i < len; i++) {
  button[i].addEventListener('click', remove, false);
}
<ul>
  <li>List item one<span> remove</span></li>
  <li>List item two<span> remove</span></li>
  <li>List item three<span> remove</span></li>
  <li>List item four<span> remove</span></li>
  <li>List item five<span> remove</span></li>
  <li>List item six<span> remove</span></li>
</ul>

关于javascript 删除 div onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42274793/

相关文章:

javascript - 输入类型提交 onmouseover

html - 创建带有描述的菜单项

javascript - Vue.js:EventBus.$收到的值没有传播

javascript - 在本地主机上使用 TLS 的 Web gRPC

javascript - 在 vue.js 应用程序中使用浏览器后退/前进按钮

javascript - 如何在 asp.net 中使用 Javascript 永久禁用按钮?

html - 做 HTML5 复选框的正确方法

javascript - 在头部添加html

jquery - 更改动态生成的链接上的文本

javascript - jquery 日期选择器中的疯狂行为