繁体   English   中英

为什么$ .load(handler(eventObject))对于Ajax请求后从服务器返回的数据不起作用,试图使其等待所有图像加载

[英]Why does $.load( handler(eventObject) ) not work for data returned from server after Ajax request, trying to make it wait for all images to load

我需要继续显示加载的gif,直到返回的数据(html)中的所有图像都已加载完毕。 数据和所有内容均已正确返回,但是.live('load',function(){})从未执行,并且也尝试了没有.live的情况。 #ContentBody的内容只是替换为返回的html数据(#LoadingLayer当然也消失了),我可以看到图像照常加载。

<script type="text/javascript">


    $("#RightLink").click(function (event) {
        event.preventDefault();

        var tourl = $(this).attr('data-ajax-url');


        $.ajax({
            type: "POST",
            url: tourl,
            dataType: "html",

            async: true,
            beforeSend: function () {
                $("#LoadingLayer").show(); //show layer with image loading gif
                $('#ColumnContainer').hide();
            },
            success: function (data) {

                $('#ContentBody').html(data).live('load', function () { $("#LoadingLayer").hide(); });
            }
        });
    });

</script>

HTML布局:

<body>

    <div id="ContentBody">

    <a id="RightLink" href="/store/ContentBodyGenerator" />

    <div id="LoadingLayer"><img src="loading.gif" /></div>

    <div id="ColumnContainer">... Main contents, lots of images here</div>

    </div>

</body>

为什么不直接隐藏#LoadingLayer

$('#ContentBody').html(data);
$("#LoadingLayer").hide();

编辑:

我误解了您的问题,我认为没有一种简单的方法可以检测到所有图像均已加载。 我建议您尝试使用waitForImages插件。

尝试将“成功”功能的内容更改为此...

$('#ContentBody').html(data).live('load', function () {
    var imgcount = $(this).find("img").length;
    $(this).find("img").one("load", function() {
        imgcount--;
        if (imgcount == 0) {
            $("#LoadingLayer").hide();
        }
    }).each(function() {
        if (this.complete) $(this).load();
    });
});

它等待直到html(data)被加载,然后获得图像计数。 然后,它将事件处理程序添加到每个图像,以在加载图像时减少图像计数。 one("load"代码意味着只允许以下代码运行一次,并且each代码基本上都说“如果已经加载(根据缓存的图像),则运行加载事件”。

一旦图像计数为0,它将隐藏加载层。

如果没有可以在控制台上运行的URL,我不能100%确信它是准确的,因此可能需要摆弄它。 如果您遇到困难,请给我们喊一声。

尝试将加载事件绑定到图像。 跟踪已加载的数量,并在它们全部加载后才删除加载层。 这是未经测试的代码,但是应该给您一个想法:

success:function(data){
    // Set the content
    $('#ContentBody').html(data);

    // How many images do we have?
    var images = $('#ContentBody img'),
        leftToLoad = images.size();

    // Listen for load event *FOR IMAGES*
    images.bind('load', function (){
        // Hey look we loaded one, was that the last one?
        if(--leftToLoad === 0){
            // Yep, we're done
            $("#LoadingLayer").hide();
        }
    });
}

如果您希望使用实时而不是在ajax回调中进行处理,请在$(document).ready回调中执行以下操作:

$('#ContentBody img').live('load', function(){...});

应该做到的。

干杯

暂无
暂无

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

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