简体   繁体   English

Javascript – 动态创建元素的事件委托不起作用

[英]Javascript – event delegation on dynamically created element not working

Sorry for another duplicate.对不起,另一个重复。

I'm trying to bind a click event listener to links which will be dynamically created later.我正在尝试将单击事件侦听器绑定到稍后将动态创建的链接。 Unfortunately this doesn't work:不幸的是,这不起作用:

document.querySelector('body').addEventListener('click', function(e) {
    if (e.target.tagName.toLowerCase() === 'a') {
        e.preventDefault();
        console.log("click")
    }
});

Strangely it also doesn't work on a link which is not created dynamically.奇怪的是,它也不适用于不是动态创建的链接。 It is however working on the body , but that's not the target.然而,它正在对body起作用,但这不是目标。

I also tried if (e.target.classList.contains("someclass")) {}我也试过if (e.target.classList.contains("someclass")) {}

The DOM nodes are body->header->div->a if that makes a difference. DOM 节点是body->header->div->a如果有区别的话。 (?) (?)

Thanks for any advice on how to make it work!感谢您提供有关如何使其工作的任何建议!

When using target , sometimes the target is not the expected element.使用target时,有时目标不是预期的元素。
See for example this code: the dynamically generated <a> have inner <span> Elements.例如看这段代码:动态生成的<a>有内部<span>元素。
On click the target will be that span .单击时, target将是那个span

To get around that minor problem we can use the .closest() selector, in both cases, span or no span:为了解决这个小问题,我们可以使用.closest()选择器,在这两种情况下,跨度或无跨度:

 document.querySelector('body').addEventListener('click', function(e) { if (e.target.closest('a')) { // All oyu need e.preventDefault(); console.log("click") } }); setTimeout(() => { document.querySelector("#links").insertAdjacentHTML("beforeend", ` <a href="#"><span>One</span></a> <a href="#"><span>Two</span></a> `); }, 1000);
 <header><div id="links"></div></header>

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

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