关于带按钮的模板字符串循环的建议
Advice on Template String Loop with Buttons
我目前正在开发一个小型 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}`);
});
您正在使用 querySelector() 方法,该方法 returns 它找到的第一个元素。如果您想将该侦听器附加到您需要使用 Document.querySelectorAll() 的所有行。您需要区分选择了哪一行,这似乎不在您的 DOM 模型中。所以我会在你的按钮上添加一个 data-product-id
属性,监听器可以使用它来知道哪个产品被删除了。
感谢大家对此的帮助。
SelectAll 在某种程度上起作用,但我决定使用 DOM 元素从头开始重做我的代码以附加子对象。完成后,这让一切变得简单多了。决定更改它,让我自己更灵活地使用代码。
我目前正在开发一个小型 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}`);
});
您正在使用 querySelector() 方法,该方法 returns 它找到的第一个元素。如果您想将该侦听器附加到您需要使用 Document.querySelectorAll() 的所有行。您需要区分选择了哪一行,这似乎不在您的 DOM 模型中。所以我会在你的按钮上添加一个 data-product-id
属性,监听器可以使用它来知道哪个产品被删除了。
感谢大家对此的帮助。
SelectAll 在某种程度上起作用,但我决定使用 DOM 元素从头开始重做我的代码以附加子对象。完成后,这让一切变得简单多了。决定更改它,让我自己更灵活地使用代码。