[英]Dynamic Event Listener Working only on the Last Created Element
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. 我正在尝试将事件侦听器添加到一堆动态创建的div中,但是由于某种原因,它仅在最后创建的div中起作用。 How to make the event listener work in all divs?
如何使事件侦听器在所有div中工作?
Update 更新资料
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)});
}
Thanks 谢谢
That's because you are modifying innerHTML
of the wrapper element. 那是因为您正在修改wrapper元素的
innerHTML
。 After modification the innerHTML
is parsed and the new Nodes are generated. 修改后,将解析
innerHTML
并生成新的Node。 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. 由于旧节点已被新节点替换,因此先前迭代中绑定到(现在已删除)元素的事件侦听器将无法工作。
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). 您应该使用事件委托技术,或者使用
document.createElement
方法生成元素,并使用wrapper元素( #window
元素)的.appendChild
附加它们。
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);
}
Correct me if I'm wrong but it looks like you're setting the ID of your div element equal to i, and not '#row' + i. 如果我错了,请更正我,但看起来您正在将div元素的ID设置为i,而不是“ #row” + i。
Also, this is an instance where jQuery would help immensely. 此外,这是jQuery可以提供极大帮助的一个实例。 Not to be that guy, but you could very easily just do
不是那个家伙,但是你可以很容易地做
$('.detail-view').click(function() { /* code */ });
Edit Anyways, your problem here is function scope in javascript. 编辑不管怎么说,你的问题就在这里是在JavaScript函数范围内。 i will always = total in your case, even after the for loop executes.
即使在for循环执行后,我也总是= total。 I created a closure for this.
我为此创建了一个关闭。
Check out this jsfiddle. 看看这个jsfiddle。 https://jsfiddle.net/jr9gzvda/
https://jsfiddle.net/jr9gzvda/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.