[英](Javascript) Re-Initialize Loop after adding some elements via "document.createElement("div")"
I am currently struggling with a problem, that's pretty hard to describe for me, but I try my best.我目前正在努力解决一个问题,这对我来说很难描述,但我会尽力而为。
I built a loop which looks like this:我建立了一个看起来像这样的循环:
for (var j = 0; j < button_remove_ingredient.length; j++) {
button_remove_ingredient[j].addEventListener("click", () => {
button_remove_ingredient = document.querySelectorAll(".remove_ingredient");
document.querySelectorAll(".ingredient_list")[j].remove();
})
}
The problem is that the loop is loading after the moment the DOM is created and in this time button_remove_ingredient
has the length of 1
because there is only one button in the HTML.问题是循环在创建 DOM 之后加载,此时
button_remove_ingredient
的长度为1
,因为 HTML 中只有一个按钮。
There is another function, which creates clones of that button after pressing another button.还有另一个功能,它在按下另一个按钮后创建该按钮的克隆。
So in this case, it's possible to have several button_remove_ingredient
but only if the user really interacts with the interface.所以在这种情况下,可能有几个
button_remove_ingredient
,但前提是用户真正与界面交互。
Now, only the first button fires the eventListener
, the other ones not and when I console.log(j)
inside the eventlistener
, it will always show me 1
.现在,只有第一个按钮会触发
eventListener
,其他按钮不会触发,当我在eventlistener
中使用console.log(j)
时,它总是会显示1
。
I wanted to try that with a foreach
loop but it didn't work either.我想尝试使用
foreach
循环,但它也不起作用。
I would be very glad if somebody did understand my problem and has a good solution for that.如果有人确实理解我的问题并对此有很好的解决方案,我会非常高兴。
I used an eventListener
checking the classList
of the event target in order to remove it.我使用
eventListener
检查事件目标的classList
以将其删除。
Please check snippet below:请检查以下片段:
document.body.addEventListener('click', () => { if(this.event.target.classList.contains("remove_ingredient")){ this.event.target.remove() } }, true); function addButton(){ document.getElementById("container").innerHTML += '<button class="remove_ingredient">New Button</button>'; }
<div id="container"> <button class="remove_ingredient">Button 1</button> <button class="remove_ingredient">Button 2</button> <button class="remove_ingredient">Button 3</button> </div> <button onclick="addButton()">Add new button</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.