英文:
Add click events to newly added elements in pure JS
问题
我想要为具有类名 item
的元素添加点击事件。在现有元素上运行良好:
const enlargables = document.querySelectorAll('.item');
enlargables.forEach(function(el) {
el.addEventListener('click', function(e) {
alert('hello');
})
});
但是,如果元素在页面加载后动态添加,事件将不会绑定到这些新元素上。
如何使用纯JS将事件添加到新添加的具有类名 item
的元素?类似于jQuery中的document.ready
的工作方式。
英文:
I want to add a click event to elements with class item
. Work fine:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const enlargables = document.querySelectorAll('.item');
enlargables.forEach(function(el) {
el.addEventListener('click', function(e) {
alert('hello');
})
});
<!-- language: lang-html -->
<div class="item">test 1</div>
<div class="item">test 2</div>
<!-- end snippet -->
But if the element is added dynamically after pageload, the event will not be added to the element.
How can I add the event to newly added elements with class item
using pure JS? Similar to how document ready works in jQuery.
答案1
得分: 1
这是发生的原因是因为您的 .item 元素是动态创建的。换句话说,它是在您的侦听器已分配后稍后附加到 DOM 的。甚至应该使用委派来实现这一点
JavaScript:
document.addEventListener("click", function(e){
const hasClass = event.target.classList.contains('item');
if(hasClass) {
//在这里添加您的逻辑
}
});
jQuery:
$('body').on('click', '.item', (event) => {
//在这里添加您的逻辑
});
英文:
This is happening because your .item element is dynamically created. In other words, it is attached to the DOM later after your listeners are already assigned. Even delegation should be used to achieve this
JavaScript:
document.addEventListener("click", function(e){
const hasClass = event.target.classList.contains('item');
if(hasClass) {
//Add your logic here
}
});
jQuery:
$('body').on('click', '.item', (event) => {
//Add your logic here
});
答案2
得分: 1
你可以在最近的静态祖先上使用事件代理。
英文:
You can use event delegation on the nearest static ancestor.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// document only used for demonstration
document.addEventListener('click', e => {
// use .closest instead to handle clicks on the descendants of .item
if (e.target.matches('.item')) console.log('click');
});
document.querySelector('button').addEventListener('click', function(e) {
const newItem = document.createElement('div');
newItem.classList.add('item');
newItem.textContent = 'test';
this.before(newItem);
});
<!-- language: lang-html -->
<div class="item">test 1</div>
<div class="item">test 2</div>
<button>Add</button>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论