在容器中添加新元素后,事件触发丢失。 示例代码如下。取消注释最后一行 Javascript 后事件丢失
您知道原因以及如何解决此问题吗?
<div class="container">
<button class="test-item">text</button>
<button class="test-item">text</button>
<button class="test-item">text</button>
<button class="test-item">text</button>
</div>
var allItems = Array.from(document.querySelectorAll('.test-item'));
allItems.forEach(function(item){
item.addEventListener('click', function(){
console.log("Go!");
});
});
var template = "<button class='test-item'>New button</button>";
//document.querySelector('.container').innerHTML += template;
最佳答案
重写代码,添加一个新按钮:
var template = document.createElement("button");
template.className = "test-item";
template.innerHTML = "New Button";
document.querySelector('.container').appendChild(template);
最有可能发生的情况是,当您在容器的内部 html 上使用 +=
时,它会完全重新创建子内容。因此,创建了一组全新的按钮,导致任何先前的事件处理程序不再工作。
关于javascript - 添加新 HTML 项目后丢失事件触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52742853/