且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jquery:ajax加载内容全部加载时的事件(包括图像)

更新时间:2023-12-05 08:25:28

你需要在将它们插入dom之前定位ajax调用的结果。

You need to target the results of the ajax call before inserting them in the dom.

因此你需要使用jQuery提供的回调方法。

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());
    });

});

http://www.jsfiddle.net/gaby/Sj7y2/

如果ajax响应中有多个图像,并且您希望在加载所有时收到通知,请使用此略微修改的版本

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());
    });

});

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..