jquery:ajax加载内容全部加载时的事件(包括图像)
我正在通过ajax加载一些html,我需要一个事件来捕获新图像加载时…
因为它在div而不是整页,我不能使用$(window).load(....
我尝试了以下但它不起作用:
$('.banners_col img:last').load(function(){.....
在将它们插入dom之前,您需要定位ajax调用的结果。
因此,您需要使用jQuery提供的回调方法。
$('#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 = $('').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()); }); });
http://www.jsfiddle.net/gaby/Sj7y2/上的示例
如果ajax响应中有多个图像,并且您希望在加载所有图像时收到通知,请使用此略微修改的版本
$('#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 = $('').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()); }); });
例子在http://www.jsfiddle.net/gaby/Sj7y2/1/
如果删除注释和空行,则代码不多:)所以不要被吓倒..
尝试使用live函数从ajax触发html元素的事件
$('.banners_col img:last').live('change',function(){.....