首页 > 解决方案 > 使用其中的按钮删除 dom 元素,vanilla JS

问题描述

我对此很陌生,并且一直在寻找一种方法来使用分配的 eventListener 制作一个“删除”按钮,以删除它相关的元素(li)。

我还不知道 JS,所以这可能不是最好的方法,但这就是我目前所拥有的:

一个简单的 HTML

<h1>The List</h1>
<ul>
  <li>Delete me<button id="del">x</button></li>
  <li>Delete me too<button id="del">x</button></li>
</ul>

我想让每个 'del' 按钮删除它的父级 - 'li' 这个按钮嵌套在哪里......我想编写一个可重用的函数。

我可以得到一个想法,我需要“使点击功能删除父(ul)的子(li)”。如何将特定的“li”与嵌套在其中的“按钮”连接起来?

我也在想可能是循环给它一个唯一的id或一个数字。我在这里有点迷路,你能建议我做什么,考虑到我真的很新,还不能做任何框架,只是希望能够在 JS 中做到这一点。

我做了这个尝试,但这太具体了,最终它需要在不知道顺序的情况下对它们中的任何一个重复使用:

const parent = document.getElementsByTagName('ul')[0];
const child = parent.getElementsByTagName('li')[0];
const del = document.getElementById('del');

function removeMe() {
  parent.removeChild(child);
}

del.addEventListener('click', removeMe);

谢谢!

标签: javascriptdombuttonevent-listenerremovechild

解决方案


因为您想在多个按钮上添加相同的逻辑,所以您应该使用classes而不是ids. ID 应该是唯一的。使用Element.closest()您可以从单击发生的位置找到最近的父级,直到找到与提供的选择器字符串匹配的节点。在此处阅读代码示例中的注释

const deleteButtons = document.querySelectorAll('.del'); // will give you an array of buttons

deleteButtons.forEach( button => {
  button.addEventListener('click', removeMe); // add the event listener to each button
});

function removeMe() {
   this.closest('li').remove(); // this is the button, from there you want to move up in DOM and find the closes <li> to remove
}
<h1>The List</h1>
<ul>
  <li>Delete me<button class="del">x</button></li>
  <li>Delete me too<button class="del">x</button></li>
</ul>


推荐阅读