开发者

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 ima开发者_开发知识库ges 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..


Try to use live function to trigger event for html elements from ajax

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜