无法让 jQuery 以正确的顺序执行代码

Can't get jQuery to execute code in the correct order

本文关键字:顺序 执行 代码 jQuery      更新时间:2023-09-26

我遇到了一些排序问题。我有一些代码可以执行以下操作:在页面加载时,循环访问 3 个表并从服务器获取内容并用所述内容填充表使表响应式

我在完成这项工作时遇到了问题。我可以通过检查元素(调用函数)来实现这个精细,但这对用户不友好。我想知道是否有办法选择正在执行的函数的排序。到目前为止,我所拥有的是:

$(document).ready(function() {
    if (dateCounter == null){ //start calendar from today's date
        var current = new Date();
        dateChange(current, "", 0); //function one to get grab all contents
        //make table responsive
        var switched = false;
              var updateTables = function() {
                if (($(window).width() < 992) && !switched ){
                    console.log("window width < 992px");
                  switched = true;
                  $("table.responsive").each(function(i, element) {
                      console.log("splitting table up");
                    splitTable($(element));
                  });
                  return true;
                }
                else if (switched && ($(window).width() > 992)) {
                  switched = false;
                  $("table.responsive").each(function(i, element) {
                    unsplitTable($(element));
                  });
                }
              };
        function splitTable(original){...}
        function unsplitTable(original){...}
    }
});

理论上,在页面加载时,它应该首先填充表,然后使表响应,但事实并非如此。它似乎同时呈现所有内容,因此我的表中有很多丢失/隐藏的内容。我不知道我的 dateChange 函数中的 AJAX 调用是否与阻止我的表正确显示内容有关。

以下是 dateChange 函数的代码片段:

function dateChange(dateInput, nGuests, vName){
    //format dates
    //For each table (3 tables)
    $(".title").each(function(index, element) {
    //prepare HTML for grabbing content from server
        //Grab content from server and pop into table
        $.ajax({
          url: "/grab_Content.asp?boatType="+boatName+"&date="+dateInput+"&guests="+guests+"&boatName="+vName+"",
          dataType:"html",
          success: function(data){
              table.html(data);
          }
        });
    });
}

是的,AJAX 调用是异步的。 $.ajax返回可用于控制序列的承诺。 首先,返回来自dateChange的承诺:

function dateChange(dateInput, nGuests, vName){
    return $.ajax({
      //...
    });
}

然后当你调用它时:

dateChange(current, "", 0).then(function() {
    //make table responsive
    var switched = false;
    //....
}

这将确保 AJAX 调用在使表响应之前完成。

如果您有多个 AJAX 调用,则必须将承诺存储在数组中并使用$.when

var promises = [];
$('.whatever').each(function() {
    var promise = $.ajax({ /*...*/ });
    promises.push(promise);
});
$.when.apply($, promises).done(function() {
    console.log('all done');
    // do work....
});

请注意,我们必须使用 Function.prototype.apply,因为$.when将一系列承诺视为单个承诺。