2010-12-20 94 views
7

我加载在通过AJAX一些HTML,我需要一个事件捉对新的图像加载时...jQuery的:事件当AJAX加载的内容为所有加载(包括图像)

监守它在一个div,而不是整个页面,我不能用$(window).load(....

我试过以下,但它不工作:

$('.banners_col img:last').load(function(){..... 
+2

嘿,好问题! – 2010-12-20 10:49:45

+0

Pl发布了一些样本代码amt代码 – 2010-12-20 11:32:14

回答

7

您需要针对Ajax调用的结果然后将它们插入到dom中。

所以你需要使用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 = $('<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()); 
    }); 

}); 

例如在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 = $('<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()); 
    }); 

}); 

例如在http://www.jsfiddle.net/gaby/Sj7y2/1/


如果删除的评论和空行,这是没有太大的代码:)所以不要被吓坏了..

+1

对不起,我还没有尽早回复。刚刚给这个解决方案进行了彻底的测试,几乎就在那里。我遇到的唯一问题似乎是来自缓存的图像不会导致'.load()'事件,所以在缓存图像的情况下,img_count会变得很短....任何想法? – Haroldo 2011-01-07 12:20:20

+0

@Haroldo,对我来说工作正常..如果你检查第二个链接(例子),如果你重新运行代码,load事件会被再次激发,即使它们被缓存了......你确定没有其他事情可以继续?如果你可以把你的代码的一个活生生的例子不起作用,这将是有益的。 – 2011-01-07 17:54:49

+0

这个解决方案效果很好。如果您希望在加载图像时显示“Loading ...”对话框,然后在加载最后一张图像时删除对话框,我修改了上面的代码以将load()方法附加到最后一张图像标签: $('img:last',$ live).load(function(){...}); – 2012-06-19 14:56:18

-3

尝试使用实时功能来从AJAX HTML元素触发事件

$('.banners_col img:last').live('change',function(){..... 
+3

这是错误的。 'change'事件仅对'input' /'textarea' /'select'元素触发。检查[documentation](http://api.jquery.com/change/)。 – 2010-12-20 15:42:16