Reputation: 6598
I know that .live()
is now deprecated but I cannot seem to change it and keep the functionality.
I just have a quick question about the .on()
function in jQuery. I'm currently using .live()
here
Like so:
$('table tr th').live("click", function() {
});
But, when I try and replace .live()
with .on()
it no longer works as it's supposed to.
I've tried putting in
$('table tr th').on("click", function() {
});
as well as
$('table tr').live("click", "th", function() {
});
and
$('table tr').delegate("th", "click", function() {
});
but to no avail.
Why is this and what steps can I take to make it work properly?
Upvotes: 24
Views: 14147
Reputation: 2141
Ensure that the selected element (the th/tr) exists when the page is loaded initially. The new .on won't work if this selector is added later to the DOM.
Try
$('body').on('click', 'thesSelectorForYourTriggerElement', function(){
//callback
});
Upvotes: 2
Reputation: 15616
The on()
function requires a syntactical update, you should alter your code to:
$('body').on("click", "table tr th", function()...
Check out this article for more info: http://www.andismith.com/blog/2011/11/on-and-off/
Upvotes: 31
Reputation: 95023
Try this:
$('table tr th').live("click", function() {
should be
$(document).on("click", "table tr th", function() {
That is how you would mimic the .live
call exactly. You could of course limit your selector from document to something more meaningful based on your DOM structure.
Edit:
Just to clarify, in your example, you are required to use $(document).on(...
because the table doesn't have any parents and is replaced during the life of your page.
Upvotes: 11
Reputation: 14487
I somehow guess that you are adding tr
elements into your table, not th
.
$('table').on("click", "tr th", function(){});
Upvotes: 0