views:

233

answers:

3

Hi,

i have a listener like this:

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

also, on the same page, another script dinamically add elements to the DOM in this way:

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

my problem is that the listener doesn't "listen" to these dinamically created elements.

anyone can shed a light please :'(

+4  A: 

It will listen only on elements that existed when you bound the event handler. If you want it to listen to dynamically created elements you want to use the live() function, which works with current and future elements.

axel_c
brilliant, thank you a lot!
luca
A: 

Sure.

The dynamic listener is not dynamic.

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

hooks up a listener to all existing elements.

When you add another element, you need to rerun that to make sure the new elements get the same handler hooked up.

Basically, the new elements dont get listened to because you dont attach new handlers to them ;)

TomTom
A: 

Yes, check out the JQuery Live function. Also remember to bind and unbind events. had issues where the link kept getting bound everytime it was created, but since the page was not reloading the link would have 5 or 6 click events tied to it, and was causing issues. just had to unbind events to the link.