[英]Javascript Vanilla - How to attach event listener on element inside ajax content?
If in Jquery we can simply delegate the event in <body>
like this: 如果在Jquery中,我们可以简单地在
<body>
委托事件,如下所示:
$('body').on('click', 'a[data-method]', function () {
// event action here
});
But how we do that in Vanilla Javascript? 但是我们如何在Vanilla Javascript中做到这一点?
Note: <a data-method="">
is created inside ajax content 注意:
<a data-method="">
是在ajax内容中创建的
Thanks. 谢谢。
You can add an event listener to body
, and then check to see if the event.target.matches
the desired selector: 您可以向
body
添加事件侦听器,然后检查event.target.matches
所需的选择器:
document.body.addEventListener('click', (event) => { if (!event.target.matches('a[data-method]')) return; console.log('click'); }); setTimeout(() => { const a = document.body.appendChild(document.createElement('a')); a.setAttribute('data-method', 'foo'); a.textContent = 'aaa'; }, 100);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.