[英]Why does the addEventListener property does not work on a dynamic HTMLcollection object?
I am working on a chrome extension and trying to add an event listener to a getElementsByClassName variable, in which elements are added dynamically using template strings.我正在开发 chrome 扩展并尝试将事件侦听器添加到 getElementsByClassName 变量,其中元素是使用模板字符串动态添加的。
I have tried a lot of changes in the code, but the code doesn't work.我在代码中尝试了很多更改,但代码不起作用。
The code is supposed to delete the targeted element from the array "recipeList", storing the array in localStorage and then render the updated array "recipeList" using template string to the HTML code again.该代码应该从数组“recipeList”中删除目标元素,将数组存储在 localStorage 中,然后使用模板字符串将更新后的数组“recipeList”再次渲染到 HTML 代码。
DELETE BUTTON Function删除按钮 Function
let delBtn = document.getElementsByClassName("del-btn");
for(let i = 0; i < delBtn.length; i++) {
delBtn[i].addEventListener("click", function() {
recipeList.splice(i, 1);
localStorage.setItem("recipeList", JSON.stringify(recipeList));
recipeList = JSON.parse(localStorage.getItem("recipeList"));
render(recipeList);
if(!recipeList.length) {
tabBtn.style.width = "100%";
delAllBtn.style.display = "none";
}
});
}
RENDER CODE渲染代码
function render(list) {
let recipeURL = "";
for(let i = 0; i < list.length; i++) {
recipeURL += `
<div class="mb-2 row">
<div class="col-1 num-btn">
${i+1}
</div>
<div class="col-10">
<div class="recipe-url">
<a target="_blank" href="${list[i]}">
${list[i]}
</a>
</div>
</div>
<div class="col-1 del-btn">
<a href="#">
<i class="bi bi-trash-fill"></i>
</a>
</div>
</div>
`
}
urlList.innerHTML = recipeURL;
console.log(delBtn);
}
When you render, you create new .del-btn
which are not included in your first let delBtn = document.getElementsByClassName("del-btn");
渲染时,您会创建新
.del-btn
,它不包含在您的第一个let delBtn = document.getElementsByClassName("del-btn");
. .
Each time you create new .del-btn
, you should also add a new listener.每次创建新
.del-btn
时,还应该添加一个新的侦听器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.