简体   繁体   English

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

[英]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 images are loaded... 我正在通过ajax加载一些html,我需要一个事件来捕捉新图像加载时...

becuase it's in a div and not a whole page, I can't use $(window).load(.... 因为它在div而不是整页,我不能使用$(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. 在将它们插入dom之前,您需要定位ajax调用的结果。

So you need to use the callback method provided by jQuery for this reason. 因此,您需要使用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());
    });

});

example at http://www.jsfiddle.net/gaby/Sj7y2/ 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 如果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());
    });

});

example at http://www.jsfiddle.net/gaby/Sj7y2/1/ 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.. 如果删除注释和空行,则代码不多:)所以不要被吓倒..

尝试使用live函数从ajax触发html元素的事件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM