【问题标题】:How to wait for all jquery loads to finish如何等待所有 jquery 加载完成
【发布时间】:2018-11-23 07:20:07
【问题描述】:

使用 Jquery,我将 id 以“lib_”开头的 div 替换为另一个文件中的 html。这一切都很好,但我需要等到它们都完成后再继续编写代码。带有“lib_”的 div 的数量可以没有,也可以很多。我在这里没有等待,它会在 .load 完成之前启动 LoadStepPart5。

let deferreds = [];

    $('[id^="lib_"]').each(function(){
        let divID = $(this).attr('id');
        let libID = divID.replace('lib_','');

        deferreds.push( $( '#' + divID ).load( "lib/library.html #" + libID, function(){
            console.log("this appears later, code didn't wait");
        }));
    });

    $.when.apply(null, deferreds).done(function() {
        console.log("immediately displayed");
        LoadStepPart5(n,xml);
    });

【问题讨论】:

    标签: jquery load jquery-deferred


    【解决方案1】:

    $.load 遵循标准的 jquery 链接,因为它返回调用选择器的 jquery 对象。例如$("#id").load("url", callback).show(); 将立即显示#id

    你期待一个返回promise的方法:$.ajax

    您可以在浏览器控制台中快速确认:

    $("#a").load("url")
    n.fn.init {context: document, selector: "#a"}
    
    $.ajax({ url: "url" })
    {readyState: 1, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
    

    将您的代码更新为:

    deferreds.push(
        $.ajax(
          { 
            url: "lib/library.html"
          })
          .done(function(html) {
            $("#"+divID).html($("<div>").html(html).find("#"+libID).html());
             console.log("this as html is loaded");
          })
     );
    

    【讨论】:

    • 这个答案解决了我的问题并教会了我一些东西。谢谢!
    【解决方案2】:

    $(window).on('load', function()

    {

    // 代码在这里

    });

    【讨论】:

    • 如果你使用 jquery 1.7 或更低版本,你可能会像 $(document).load(function() { // code here });
    猜你喜欢
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2015-04-17
    • 2017-02-06
    相关资源
    最近更新 更多