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?
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. 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.
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);
}
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.
Also, this is an instance where jQuery would help immensely. 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. i will always = total in your case, even after the for loop executes. I created a closure for this.
Check out this jsfiddle. https://jsfiddle.net/jr9gzvda/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.