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

2023-11-26

我正在通过ajax加载一些html,我需要一个事件来捕捉新图像加载时的情况...

因为它在一个 div 中而不是整个页面中,所以我不能使用$(window).load(....

我已尝试以下方法,但它不起作用:

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

在将 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 响应中有多个图像,并且您希望在何时收到通知all加载其中的然后使用这个稍微修改的版本

$('#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/


如果删除注释和空行,代​​码就不多了:)所以不要被吓倒..

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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