jquery: event for when ajax loaded content is all loaded (including images)
I'm loading in some html via ajax, I need an event to catch on to when the new images are loaded...
becuase it's in a div and not a whole page, I can't use $(window).load(....
I've tried the following but it doesn't work:
$('.banners_col img:last').load(function(){.....
You need to target the results of the ajax call before inserting them in the dom.
So you need to use the callback method provided by jQuery for this reason.
$('#load').click(function(){
// inside the handler that calls the ajax
//you ajax call here
$.get('the_url_to_fetch',function(data){
// create an in-memory DOM element, and insert the ajax results
var $live = $('<div>').html(data);
// apply a load method to the images in the ajax results
$('img',$live).load(function(){
// what to do for each image that is loaded
});
// add the ajax results in the DOM
$('selector_where_to_put_the_response').html($live.children());
});
});
example at http://www.jsfiddle.net/gaby/Sj7y2/
If there are multiple images in the ajax response and you want to get notified when all of them are loaded then use this slightly modified version
$('#load').click(function(){
// inside the handler that calls the ajax
//you ajax call here
$.get('the_url_to_fetch',function(data){
// create an in-memory DOM element, and insert the ajax results
var $live = $('<div>').html(data);
// count the number of images
var imgCount = $live.find('img').length;
// apply a load method to the images in the ajax results
$('img',$live).load(function(){
// what to do for each image that is loaded
imgCount--;
if (imgCount==0)
{
// the code in here is called when all images have loaded.
}
});
// add the ajax results in the DOM
$('selector_where_to_put_the_response').html($live.children());
});
});
example at http://www.jsfiddle.net/gaby/Sj7y2/1/
If you remove the comments and the empty lines, it is not much code :) so do not get intimidated..
尝试使用实时功能从ajax触发HTML元素的事件
$('.banners_col img:last').live('change',function(){.....
链接地址: http://www.djcxy.com/p/49412.html
上一篇: 加载Javascript:HTTP请求