在不丢失事件监听器的情况下克隆节点

cloneNode without losing event listener

如何移动我的 html 元素而不丢失附加到按钮的事件侦听器?

克隆并删除原始元素后,子按钮的事件侦听器不起作用

ul.appendChild(element.cloneNode(true));
element.remove();

您说过要移动它,但您所做的是克隆它,保存克隆,然后删除并丢弃原始文件。相反,不要克隆它,移动它:

ul.appendChild(element);

这将从其当前父级中删除 element 并将其放入其新父级 (ul),所有事件侦听器仍然存在。

实例:

// NOTE: This isn't how I'd write this code if I weren't demonstrating
// the fact the listeners are retained when the element is moved.
// But without context, it's hard to show a delegation solution.

const list1 = document.getElementById("list1");
const list2 = document.getElementById("list2");

// Add a listeneer to each `li`
document.querySelectorAll("li").forEach((li, index) => {
    li.addEventListener("click", () => {
        console.log(`Moving "${li.textContent}" which was originally at index ${index}`);
        if (li.closest("ul") === list1) {
            // Move from list1 to list2
            list2.appendChild(li);
        } else {
            // Move from list2 to list1
            list1.appendChild(li);
        }
    });
});
li {
    cursor: pointer;
}
<div>List 1:</div>
<ul id="list1">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>
<div>List 2:</div>
<ul id="list2">
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
</ul>
<div>Click an item to move it to the other list.</div>


也就是说,我经常发现在处理在父元素之间移动的元素时,事件委托是最好的,但这实际上取决于具体情况。