0
$.get('page.php', function(data){
   $('#container').append(data);
});

$('.delete').click(function(){
 alert();
});

I have a page use get to fetch & append more data into the page,

in my main page, i have a button script for class delete, this works for all button in main page, but not the new data append into, is any way to solve this problem?

Ben
  • 2,422
  • 7
  • 31
  • 59

1 Answers1

0

This is an event delegation issue. The click handler is only set on elements present at the time the code is executed.

Try:

$('body').on('click', '.delete', function(){
 alert();
});

body is here just a placeholder for any parent element of .delete. Try to attach the handler to a parent element with as less child elements as possible (in your example #container seems appropriate) to prevent performance issues.

Community
  • 1
  • 1
markusthoemmes
  • 2,915
  • 12
  • 22
  • Should really be using `$('#container').on(...);` so it's bound as close to the dynamic elements as possible. – Anthony Grist Feb 06 '14 at 13:04
  • Yeah i'm aware of that, but i wanted to briefly explain the issue + we do not know if the OP has some other elements to be added, that won't be children of `#container`. But it's a fair point as i have mentioned. – markusthoemmes Feb 06 '14 at 13:07