我有一个组件BagPage,其中包含一些子组件,这些子组件将在getBagByIdAsync Promise解析后呈现,并且我想在这些子组件之一中的某些元素在呈现后立即添加单击事件侦听器,但会不断获取:>
无法读取null的属性'addEventListener'
这意味着我试图在DOM中的元素存在之前添加事件侦听器。
这是我的代码:
function listenToBagRemove(bag) {
bag.items.forEach(item => {
document
.querySelector(`#remove${item.id}`)
.addEventListener('click', () => {
return BagService.deleteItemByIdAsync(bagId, item.id);
});
});
}
async function BagPage(bagId) {
let bag;
try {
bag = await BagService.getBagByIdAsync(bagId).then(res => {
listenToBagRemove(res);
});
} catch (e) {
console.log(e);
return '<div class="error">Error loading bag items...</div>';
}
return `<div class="page">
${Header(bag.items)}
${ProductsList(bag.items)}
${Footer()}
</div>`;
}
export default BagPage;
以及产品列表中每个产品卡的代码:
const ProductCard = item => `<div class="product-card">
<div class="remove-btn" id="remove${item.id}">
<img src="${closeIcon}" />
</div>
<div class="image-container">
<img class="image" src="${item.image}" />
</div>
<div class="info-container alignCenter">
<div class="brandName">${item.name}</div>
<div class="price">€${item.price}</div>
</div>
</div>`;
export default ProductCard;