2

I understand that .live() has been removed from jQuery 1.9 and that .on() should be used instead. So far .on() has worked perfectly for me if the selector is a string. For example,

$("a.offsite").live("click", function(){ alert("Goodbye!"); });

turned into

$(document).on("click", "a.offsite", function(){ alert("Goodbye!"); });

But how do I use .on() for a JQuery selector object (or a collection of objects) as follows?

var jele = $('.nav').find("a.offsite");
$(jele).live("click", function(){ alert("Goodbye!"); });

turned into

var jele = $('.nav').find("a.offsite");
$(document).on("click", jele, function(){ alert("Goodbye!"); });

Is the code above converted correctly? The problem I encounter is other event handlers bound to the same event yet different selector are also executed when the event fires. Hence I suspect this is not the correct way but I can't find any similar example in the official documentation.

I know I could have passed the selector string instead of the jele object into .on() method but in some cases I simply do not have access to the selector string, eg. when the jele object is passed as an argument into the function in which the binding occurs.

Liam
  • 27,717
  • 28
  • 128
  • 190
shengloong
  • 85
  • 1
  • 5
  • 8

3 Answers3

0

Once you've got the JQuery jele object, try to call the .on() function on jele:

$(jele).on("click", your-code-here);

Other way to do it is having the selector string of jele. Check out this post I found about retrieving the selector string of any JQuery object. Once you have the jele selector string, your code should be as follows:

$(document).on("click", selector, your-code-here);
Community
  • 1
  • 1
JordiVilaplana
  • 485
  • 3
  • 9
  • Thanks but this will not work if jele's html element has not existed yet (eg. loaded using AJAX). That's the reason why I used .live() initially. To quote the documentation, "Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()." – shengloong May 22 '13 at 09:20
  • Okay, I understand you now. Let me edit my answer and I hope I can help you. – JordiVilaplana May 22 '13 at 09:37
0
$(jele).on("click", function(){ alert("Goodbye!"); });
saifur
  • 637
  • 4
  • 17
0

.on() replace .bind(), .live() and .delegate()

usage:

$('div').on('click',function(){/* ... */}); //equivalent to .bind()

this 3 lines are equivalent:

$('a','#menu').live('click',function(){/* ... */});
$('#menu').delegate('a','click',function(){/* ... */}); 
$('#menu').on('click','a',function(){/* ... */}); 
Yukulélé
  • 15,644
  • 10
  • 70
  • 94