我目前正在开发一个迷你 Web 应用程序,希望得到一些建议。我知道我的问题的原因,我知道解决它的一种方法,但这意味着取消我已经完成的很多工作。
我遇到的问题是我目前在 for 循环中使用模板字符串来打印数据,并且我有一个带有侦听器的删除按钮。目前它仅适用于列表中的最后一个按钮,我知道这是因为每次使用 html = x 时我都会破坏 innerHTML。
我想知道的是....有没有一种简单的方法可以解决这个问题,或者我应该使用 append child 等代替吗?
for(let prod of products){
console.log("Doc ID",doc.id);
const li1 = `
<p><div>${prod.name} <div class="right"><font class=pink-text>Location:</font> $${prod.location} <button data-remove-button-id="${doc.id}" class="btn-remove">Delete</button></div></div></p>
`;
html += li1;
} //end for loop
const li2 = `
<br />
<button class="btn blue darken-2 z-depth-0 right modal-trigger" data-target="modal-prodedit">Add/Edit Attributes</button><br />
</div>
</li>
`;
html += li2;
productList.innerHTML = html;
const removeBtn = document.querySelector(`[data-remove-button-id="${doc.id}"]`);
console.log("removeBTN",removeBtn);
removeBtn.addEventListener('click', (e) => {
e.preventDefault();
console.log(`deleted row ${e.target.dataset.removeButtonId}`);
});
慕的地10843
慕侠2389804
相关分类