问题描述
我正在尝试向一堆动态创建的 div 添加事件侦听器,但由于某种原因,它只能在最后创建的 div 中工作.如何让事件监听器在所有 div 中工作?
I'm trying to add event listeners to a bunch of dynamically created divs, but for some reason it only work in the last created div.How to make the event listener work in all divs?
更新
for (var i = 0; i < total; i++)
{
row_string = row_string+ "<div id='row" + i + "' class='detail-view'></div>";
document.getElementById('window').innerHTML = document.getElementById('window').innerHTML+row_string;
document.getElementById('row'+i).addEventListener('click', function() {openRow("#row"+i)});
}
谢谢
推荐答案
那是因为您正在修改包装元素的 innerHTML
.修改后,解析 innerHTML
并生成新的节点.由于旧节点被新节点替换,之前迭代中绑定到(现已删除)元素的事件侦听器将无法工作.
That's because you are modifying innerHTML
of the wrapper element. After modification the innerHTML
is parsed and the new Nodes are generated. Since the old Nodes are replaced with the new Nodes, the event listeners that had been bound to the (now deleted) elements in the previous iterations won't work.
您应该使用事件委托技术或使用 document.createElement
方法生成元素并使用包装元素的 .appendChild
附加它们(#window
元素).
You should either use the event delegation technique or generate the elements using document.createElement
method and append them using the .appendChild
of the wrapper element (the #window
element).
这是第二种建议方法的示例:
Here is an example of the second suggested method:
function openRow(event) {
var id = this.id;
// ...
}
var el, win = document.getElementById('window');
for (var i = 0; i < total; i++)
{
el = document.createElement('div');
el.classList.add('detail-view');
el.id = 'row_' + i;
el.addEventListener('click', openRow);
win.appendChild(el);
}
这篇关于动态事件侦听器仅在最后创建的元素上工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!