If in Jquery we can simply delegate the event in <body>
like this:
$('body').on('click', 'a[data-method]', function () {
// event action here
});
But how we do that in Vanilla Javascript?
Note: <a data-method="">
is created inside ajax content
Thanks.
You can add an event listener to body
, and then check to see if the event.target.matches
the desired selector:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.