Javascript/JQuery - 如何在完成前一个函数时调用一个函数

Cod*_*ger 5 javascript jquery deferred

我正在使用以下Javascript函数来显示图片库.

function disp_pics(currObj,table){
    if(currObj != "none"){
        $("div .checkout2").removeClass("checkout2").addClass("checkout");
        $(currObj).closest("div").removeClass("checkout").addClass("checkout2");
    }

    function getData(table){
        return $.ajax({
            url: "newphoto_gallery_display.php",
            type: "GET",
            data: {
                table: table
            },
            dataType: "html"
        });
    }

    function display_result(data){
        var dfd = new $.Deferred();
        dfd.done(equalise);
        $("#ajaxoutput").html(data);
        setTimeout(function() {
            dfd.resolve();
        }, 1000);
    }

    function equalise(){
        var highestBox = 0;
        $('.photodisplay').each(function(){
            if($(this).height() > highestBox)  {
                highestBox = $(this).height(); 
            }
        });  
        $('.photodisplay').height(highestBox);
    }

    var promise=getData(table);
    promise.success(function (data) {
        promise.done(display_result(data));
    });
};
Run Code Online (Sandbox Code Playgroud)

函数getData从数据库中获取图片数据.函数display_result然后将该数据输出到div id"ajaxoutput".图片与相关数据一起显示在框中(带边框的HTML表格).然后调用函数equalize以使所有框具有相等的高度.

如果没有display_result中的时间延迟,则在显示所有图片和数据之前调用均衡功能,从而弄乱显示器.有没有办法消除时间延迟,只有当display_result已经完成将所有数据输出到ajaxoutput div时才调用均衡函数?

我已经尝试了各种各样的Deferred和$ .when .......然后......组合,但是没有设法在不延迟脚本的情况下达到预期的结果,这是不理想的.欢迎大家提出意见.

jfr*_*d00 5

如果问题是你需要知道你所应用的HTML的所有图像何时#ajaxoutput被加载(因此浏览器已知它们的大小),那么你可以通过监视每个图像的onload事件来做到这一点.您添加到HTML的图片:

function display_result(data){
    var dfd = new $.Deferred();
    var imgWaiting = 0;
    $("#ajaxoutput").html(data).find("img").each(function() {
        if (!this.complete) {
            // img is still loading, install a load handler so we know when it's done
            ++imgWaiting;
            this.onload = this.onerror = function() {
               --imgWaiting;
               if (imgWaiting === 0) {
                   dfd.resolve();
               }
            }
        }
    });
    if (imgWaiting === 0) {
         dfd.resolve();
    }
    return dfd.promise();
}
Run Code Online (Sandbox Code Playgroud)

然后,你可以这样做:

return getData(table).then(display_result).then(equalise);
Run Code Online (Sandbox Code Playgroud)

这是一个经典的设计模式,承诺用于序列化多个异步操作.


Sco*_*tie -1

你能同步运行它们吗?

function display_result(data){
    $("#ajaxoutput").html(data);
    equalise();
}
Run Code Online (Sandbox Code Playgroud)

我很确定 .html 函数是同步调用,因此您的大小调整将在此之后发生。

编辑:来自 ajax 调用的数据是什么样的?它只是一堆img标签吗?如果是这样,您可能最好用 ajax 加载图像并自己将其编码到 html 中。