[英]addEventListener problem during Iteration of an array[solved]
我正在為我的新兵訓練營建立一個項目,但我被困在一個很煩人的小地方。 我有一個 api,我可以在其中查詢 amazon 並顯示產品,每個產品都有自己的“卡片”樣式,如果用戶選擇他想要添加,我會將每個產品推送到用戶類構造函數中的空數組將該產品添加到他的“配置文件”,在用戶類中,我有一個名為“displayProducts”的函數,它基本上迭代該產品數組,創建一個 div 元素,在每次迭代時修改元素的 innerHTML 並將其顯示在頁面上。 這是功能:
const productSection = document.getElementById('userProducts')
productSection.innerHTML = ``;
let div = document.createElement('div')
if (user.products.length > 0) {
user.products.forEach((product) => {
div.innerHTML += `
<div class="card horizontal">
<div class="card-image">
<img src=${product.img}>
</div>
<div class="card-stacked">
<div class = "card-content">
<span class = "card-title"> ${product.title} </span>
<p> ${product.rating} rating, ${product.totalReviews} reviews </p>
<span> Price:${product.price}</span>
</div>
<div class="card-action">
<button class="btn delete-${product.asin}">delete</button>
</div>
</div>
`
deleteButton = div.querySelector(`.delete-${product.asin}`).addEventListener('click', user.delete.bind(product))
productSection.appendChild(div);
}
問題是,在向每個按鈕添加事件偵聽器時 - 它只是將事件偵聽器應用於最后一個產品,即使在每個階段它都選擇了正確的按鈕,我已經使用了兩個多小時,我很失落。 我如何將事件偵聽器持久化到每個產品卡?
當您使用container.innerHTML +=
,容器內的任何現有偵聽器都將丟失,因為容器的內容會從新的 HTML 字符串開始重新解析。 另一種方法是使用insertAdjacentHTML
,它不會破壞現有元素:
div.insertAdjacentHTML('beforeend', `
<div class="card horizontal">
<div class="card-image">
<img src=${product.img}>
// etc
然后在循環內使用addEventListener
將起作用。
但我關心的另一個問題是 HTML 字符串與products
數據的連接。 除非這些數據值得信賴,否則您當前的代碼可能會導致任意代碼執行,這是一種安全風險。 而不是直接在模板文字內插值。 考慮之后選擇元素並分配給它們的textContent
(或其他屬性)。 例如,而不是:
<img src=${product.img}>
追加當前<div>
,然后分配給src
稍后。 而不是insertAdjacentHTML
:
const thisCard = div.appendChild(document.createElement('div'));
thisCard.className = 'card horizontal';
thisCard.innerHTML = `
<div class="card-image">
<img>
</div>
// etc
`;
thisCard.querySelector('img').src = product.img;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.