-1

Possible Duplicate:
jQuery - convert .live() to .on()
JQuery ‘on’ vs. ‘live’
Turning live() into on() in jQuery

I know .live() is deprecated, but .on() is getting me some errors. It does not work when I dynamically generate the dome, it only works at the first click. Whilst the same code with .live() works correctly. I'm using jquery 1.8

Working code

$('.item').live('click', function(e) {
   alert('test');
   // ajax call that regenerates .item element
});

This code only works at the first click:

$('.item').on('click', function(e) {
   alert('test');
   // ajax call that regenerates .item element
});

What's wrong?

Community
  • 1
  • 1
Daniele
  • 359
  • 7
  • 15
  • 10
    You aren't supplying a context. the context for .live is `document`. This has been asked so many times. – Kevin B Jan 08 '13 at 18:43

3 Answers3

2

Since the dom change with your Ajax you need to provide a parent on your on call like this:

$("#itemParent").on("click", ".item", function(event){
  alert('test');
});
Simon Arnold
  • 15,849
  • 7
  • 67
  • 85
2

Check the documentation here. .on works slightly different:

$(document).on("click", ".item", function(event){
    alert('test');
    // ajax call that regenerates .item element
});
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
-1

As Kevin B mentioned, use document as context of delegation, or better static parent:

$(document).on('click','.item', function(e) {
   alert('test');
   // ajax call that regenerates .item element
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155