JQuery listener does not "listen" for events on dynamically created DOM elements

I have a listener like this:

$('.delete').click(function() {
  ...some stuff
});

Also, on the same page, another script dynamically adds elements to the DOM as follows:

$('#list').append('<tr><td><a class="delete" href="#">delete</a></td></tr>');

My problem is that the listener does not "listen" to these dynamically created elements.

Can anyone shed some light?

+5
source share
4 answers

, . , , live(), .

EDIT: jQuery 1.7 . on(), .bind(), .live() .delegate(), , .

+13

, , . , , , 'on' , .

this.$someStaticParent.on('click', 'li', functionName); 

, , . , , , , , , . . , . .

+3

, JQuery Live. . , , , , 5 6 , , . .

+1
source

Of course.

A dynamic listener is not dynamic.

$('.delete').click(function() {

connects the listener to all existing elements.

When you add another item, you need to re-run this to make sure that the new items are connected to the same handler.

In principle, new elements are not tapped because you are not attaching new handlers to them;)

0
source

All Articles