DOM 添加元素后如何让事件监听器继续工作(纯js)

How to make event listener to keep working after elements are added to the DOM (pure js)

我有这个听众:

//close all detail tags when click happens outside
document.addEventListener('click', function(e) {
 if (!details.some(f => f.contains(e.target))) {
   details.forEach(f => f.removeAttribute('open'));
 } else {
   details.forEach(f => !f.contains(e.target) ? f.removeAttribute('open') : '');
 }
})

当点击一个新标签或您点击页面上的任意位置时,它会自动关闭所有打开的详细信息标签,效果很好。当动态添加新的详细信息标签时会出现问题,然后侦听器将无法为它们工作。我正在阅读其他相关问题和大多数建议的委派,但情况似乎并非如此,因为侦听器也应该适用于普通标签和动态标签。

我尝试了一些这样的建议:

document.addEventListener('click', function(e){
    if(e.target && e.target.id== 'myDynamicallyAddedElementID'){
         //my code
    }
});

但没有变化。你可以在这里测试https://jsfiddle.net/nxv03wjo/ and here https://jsfiddle.net/nxv03wjo/1/

这里有什么技巧?

只需检索点击监听器中的 details 元素?

document.addEventListener('click', function (e) {
    const details = [...document.querySelectorAll('details')];
    if (!details.some(f => f.contains(e.target))) {
        details.forEach(f => f.removeAttribute('open'));
    } else {
        details.forEach(f => !f.contains(e.target) ? f.removeAttribute('open') : '');
    }
});