jquery:ajax加载内容全部加载时的事件(包括图像) [英] jquery: event for when ajax loaded content is all loaded (including images)

查看:81
本文介绍了jquery:ajax加载内容全部加载时的事件(包括图像)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm loading in some html via ajax, I need an event to catch on to when the new images are loaded...

因为它在div中而不是整页,我不能使用 $(窗口).load(....

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(){.....


推荐答案

你需要在将它们插入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..

这篇关于jquery:ajax加载内容全部加载时的事件(包括图像)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆