How to use jQuery .live() with ajax
Currently I am using John Resig's LiveQuery plugin/function to allow users to sort through a long unordered-list of list-items. The code is as follows: $('input#q').liveUpdate('ul#teams').focus();
The issue arises when I use ajaxified tabs to sort the lists. Essentially I use ajax to pull in different lists and the liveUpdate()
function doesn't have access to the new li's.
I assume I would need to bind this using the .live()
function. But I am unclear how to bind this to an ajax event, I've only used the "click" event. How would I bind the new liveUpdate()
to the newly loaded list-items?
EDIT: The ajax tabs is run through the wordpress ajax api so the code is fairly complex, but simplified it is something like this:
$('div.item-list-tabs').click( function(event) {
var target = $(event.target).parent();
var data = {action, scope, pagination}; // Passes action to WP that loads my tab data
$.post( ajaxurl, data, function(response) {
$(target).fadeOut( 100, function() {
$(this).html(response);
$(this).fadeIn(100);
});
});
return false;
});
This is simplified for the sake of this conversation, but basically once the $.post
loads the response in place .liveUpd开发者_开发知识库ate()
doesn't have access to it. I believe the .live()
function is the answer to this problem, I'm just unclear on how to implement it with the $.post()
As mentionned in the documentation of JQuery, .live() is considered deprecated. You should use the method .on() instead.
$("#yourSelector").on("click", function() {
// statement
});
To also manage futur object of the selector type, you can use .on() like this
$(document).on("click", "#yourSelector", function() {
// statement
});
Try using jQuery's Ajax Events
$('input#q').ajaxComplete(function(){
$(this).liveUpdate('ul#teams').focus();
$(this).unbind('ajaxStop');
});
I also got trouble with using just
$('selector').click(function(..
after an Ajax call, and finally found that we need to use
$('selector').live("click", function(){..
or the new method
$(document).on('click', 'selector', function(){..
to bind the event for new elements created after an Ajax call.
$(document).on('click','selector', function(event){
//your code
});
For live
$('selector').live('click', function(event){
//your code
});
$('input#q').live(function() {
$(this).liveUpdate('ul#teams').focus();
});
$("div.item-list-tabs").live("click",function(){
//statements..
});
精彩评论