javascript - 使用其中的按钮删除 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);
谢谢!
解决方案
因为您想在多个按钮上添加相同的逻辑,所以您应该使用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>
推荐阅读
- tensorflow - 为什么相同的 TensorFlow 模型适用于数组列表,但不适用于未批处理的 tf.data.Dataset?
- real-time - 无法在 systemd 服务上设置实时优先级
- java - 查询 dsl - 如何编写有子句
- kubernetes - 如何使用 Helm Spray 重新部署 pod?
- elixir - 从列表中的结构获取值
- php - Composer 包版本冲突
- reactjs - Caddy reverse_proxy 和 React 路由器
- asp.net-core - 如何使用默认证书(Windows 10)从 gRPC C++ 客户端以 HTTPS 方式连接到 Kestrel 中托管的 gRPC 服务器?
- reactjs - 意外的单位“ms”单位允许列表,反应scss
- three.js - 在 ThreeJS 中,如何旋转顶点着色器以“查看”一个点?