简体   繁体   English

DOM只注册一个点击事件删除元素

[英]DOM only registering one click event remove element

I have a simple form, where I want to be able to remove DOM elements, that I might not need (eg. questions on a form).我有一个简单的表单,我希望能够删除我可能不需要的 DOM 元素(例如表单上的问题)。

This works only for the first element.这仅适用于第一个元素。 After the first element is removed (clicked) it will be removed but then all further clicks are not registered.删除(单击)第一个元素后,它将被删除,但不会注册所有进一步的单击。

The console will only display the first "click" as well.控制台也只会显示第一次“点击”。

I am using handlebars to generate some of the DOM elements in a loop, not sure if that would actually cause a issue, since I am able to see the elements in chrome inspector.我正在使用把手在循环中生成一些 DOM 元素,不确定这是否真的会导致问题,因为我能够在 chrome 检查器中看到这些元素。

JS FUNCTION JS函数

let allItems = document.getElementById("main");

allItems.addEventListener("click",function(e){
    console.log("click");
      e.target.parentElement.remove();
      e.preventDefault();

  });

HTML -- HandleBars. HTML——把手。

 {{#each all}}
        <div id="main">
            <p class="delete">&#x2718;</p>
            <span class="select">
                <select>
                    <option value="0"></option>Selection</option>
                </select>
            </span>
        </div>
  {{/each}}

You've got two problems here:你在这里有两个问题:

  1. you are assigning the same id to multiple elements, this is invalid html as id's are supposed to be unique.您正在为多个元素分配相同的 id,这是无效的 html,因为 id 应该是唯一的。

  2. This is a very common problem in javascript.这是javascript中一个非常常见的问题。 the code only binds event listeners on the elements that were present in the page at the time the code ran.该代码仅在代码运行时页面中存在的元素上绑定事件侦听器。 any newly added elements won't be present.任何新添加的元素都不会出现。 the solution in this scenario is to remove the event listeners off the elements, and add a single listener on the document for click, then check the event target to see if it is one of the nodes you want.这种情况下的解决方案是从元素中移除事件侦听器,并在文档上添加一个侦听器以进行单击,然后检查事件目标以查看它是否是您想要的节点之一。

I recommend to remove id of main from the elements, and give them all an identical class ie class="removable-form-item" , then use a global click listener like so:我建议从元素中删除 main 的 id,并给它们一个相同的类,即class="removable-form-item" ,然后使用全局点击监听器,如下所示:

document.body.addEventListener('click',function(event){
    if(event.target.classList.contains("removable-form-item")){
        //got a click on our target name
        // your code to remove the item here
        e.target.parentElement.remove();
        e.preventDefault();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM