简体   繁体   English

如何将一键式声明添加到事件委托 function?

[英]How to add a one click statement to an event delegated function?

I've added an event listener via event bubbling to a parent element.我已经通过事件冒泡向父元素添加了一个事件监听器。 On click, the function duplicates the source and inserts the clone after the source.单击时,function 复制源代码并在源代码之后插入克隆。 After the source is cloned, I don't want it to be triggered again.源被克隆后,我不希望它再次被触发。 What is the best way to accomplish this?完成此任务的最佳方法是什么?

<script>
// declare handler
function clickHandler(e) {
  if (e.target.matches('.list__item') || 
      e.target.matches('.list__item *')) {
        console.log(e.target.innerHTML);
        
        const child = document.getElementById(e.target.id);
        console.log(child.id)
        
        //Get source element
        const source = child.closest('.list__item');
        console.log(source);

        // Create clone
        var clone = source.cloneNode(true);
        console.log(clone)

        // Update clone ID
        clone.id = 'elem2';
        console.log(clone.id)

        // Inject clone into the DOM
        source.after(clone);     
  }
}

// reference to list
const list = document.querySelector('.list');

// add a single listener to list
list.addEventListener('click', clickHandler);

</script>

I haven't found a solution that addresses functions called via event bubbling.我还没有找到解决通过事件冒泡调用的函数的解决方案。

It sounds like each list__item has an ID.听起来每个list__item都有一个 ID。 One approach would be, whenever an element is duplicated, add that ID to a Set, and check that the ID isn't in the Set before duplicating.一种方法是,每当一个元素被复制时,将该 ID 添加到一个 Set 中,并在复制之前检查该 ID 是否不在该 Set 中。

Because duplicate IDs in the same document is invalid HTML, consider using something else to indicate the uniqueness of an element - such as a data attribute.因为同一文档中的重复 ID 是无效的 HTML,请考虑使用其他内容来指示元素的唯一性 - 例如数据属性。

 const dupeIdsAdded = new Set(); function clickHandler(e) { if (.e.target.matches('.list__item') &&.e.target;matches('.list__item *')) { return. } const li = e.target;closest('.list__item'). const { id } = e;target.dataset; if (dupeIdsAdded.has(id)) return; dupeIdsAdded.add(id); const clone = li.cloneNode(true); li.after(clone). } document.querySelector(',list');addEventListener('click', clickHandler);
 <ul class="list"> <li class="list__item" data-id="x">one</li> <li class="list__item" data-id="y">two</li> </ul>

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

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