【问题标题】:Delete a dom element using a button within it, vanilla JS使用其中的按钮删除 dom 元素,vanilla JS
【发布时间】:2021-03-11 12:35:19
【问题描述】:

我对此很陌生,并且一直在寻找一种方法来使用分配的 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);

谢谢!

【问题讨论】:

    标签: javascript dom button event-listener removechild


    【解决方案1】:

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

    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>

    【讨论】:

      【解决方案2】:

      正如其他人所说,元素 id should be unique in the document

      使用event delegationdata-attribute 来识别应该激活删除的按钮。

      document.addEventListener('click', evt => {
        const origin = evt.target;
        if (+origin.dataset.deleteparent) {
          origin.closest("li").remove();
        }
      });
      
      /* 
        --explained--
        const origin = evt.target;
                       ^ where did the click originated?
        if (+origin.dataset.deleteparent)
            ^       ^ only if the button contains data-deleteparent attribute
            ^ convert data-attribute value to Number. 
              If it's not there, or 0, nothing will happen
          origin.closest("li").remove();
                 ^ parent li   ^
                               ^ remove it
        }
      */
      button[data-deleteparent] { color: red; border: none; background-color: transparent; cursor: pointer}
      <h1>The List</h1>
      <ul>
        <li>Delete me <button data-deleteparent="1">&#x2718;</button></li>
        <li>Delete me too <button data-deleteparent="1">&#x2718;</button></li>
        <li>Delete me not <button>Do not delete</button></li>
      </ul>

      【讨论】:

      • 即使您使用不同的方法,这也会删除所有包含按钮的&lt;li&gt; 元素。您不检查 id 不是唯一的,但 id 应该是唯一的。抱歉,这需要投票
      • 调整了答案。
      • .parentNode.parentNode,编辑一点 HTML,看到应用程序失败,然后转到 JS,编辑,即:.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode 刷新它就可以了! closest 应该始终是使 JS 尽可能灵活的首选方式。
      • @RokoC.Buljan 很好。想在这里演示一下 DOM 遍历,但是,嘿,closest 也可以。
      【解决方案3】:

      只需使用 DOM 节点的 parentElement 属性即可。 此外,如上所述 - 在您的情况下,您应该使用 classes 而不是 id,因为 id 必须是唯一的。

      const buttons = document.querySelectorAll('.rm-button');
      
      function rmParent() {
         this.parentElement.remove();
      }
      
      buttons.forEach(button => {
        button.addEventListener('click', rmParent);
      });
      <h1>The List</h1>
      <ul>
        <li>Delete me<button class="rm-button">x</button></li>
        <li>Delete me too<button class="rm-button">x</button></li>
      </ul>

      【讨论】:

        猜你喜欢
        • 2018-05-07
        • 2021-12-08
        • 2023-03-24
        • 1970-01-01
        • 2021-12-19
        • 2021-05-14
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        相关资源
        最近更新 更多