Jquery:当另一个完成时执行一个函数

时间:2011-09-18 10:33:00

标签: javascript jquery animation queue jquery-animate

我需要你的帮助。 我想用jquery动画一个面板。它必须在单击按钮(函数OPEN_PANEL)上打开并在其上加载不同的php页面,然后在单击具有“close”类(功能CLOSE_PANEL)的div时关闭。 这工作正常,问题是当我想打开一个不同的面板时。它应该关闭打开的那个,然后打开我选择的最后一个,但看起来它同时执行两个功能。我该如何解决这个问题呢?

这是javascript代码:

var panel_is_open=0;
var last_open_panel="";

function animation_open_panel(id){
    window_height=$(window).height()*0.85;
    $("#"+id+"_button").css({'background-color':'rgba(255,255,255,0.8)', 'box-shadow':'0px 5px 10px #39C', '-webkit-box-shadow':'0px 5px 10px #39C'});
    $("#main_panel").show().animate({ height: window_height+"px" }, 1500)
    .animate({ width: "90%" },1000);
    $("#main_panel").queue(function(){
        $(".close").show();
        $("#page_container").hide().load(id+"/"+id+".php",function(){
            $("#page_container").fadeIn(1000);
        });
        $(this).dequeue();
    });
}

function animation_close_panel(){
    $("#page_container").fadeOut(1000, function(){
        $("#main_panel").animate({ width: "637px" }, 1000)
        .animate({ height:"0px" }, 1500, function(){
            $(".close").hide();
            $("#"+last_open_panel+"_button").css({'background-color':'', 'box-shadow':'', '-webkit-box-shadow':''});
        });
    });
}

function close_panel(){
    if(panel_is_open==1){
        animation_close_panel();
        panel_is_open=0;
    }
}

function open_panel(id){
    if(panel_is_open==0){
        animation_open_panel(id);
        last_open_panel=id;
    }

    else if(panel_is_open==1){
        if(id!=last_open_panel){
            close_panel();
            open_panel(id);
        }
    }

    panel_is_open=1;
}

非常感谢您的帮助。


非常感谢你的建议,但我无法用两种解决方案解决问题。我错了什么,但我无法理解。

这是我的代码:

function close_panel(){
    if(panel_is_open==1){
        // animations here
        panel_is_open=0;
    }
}

function close_open_panel(next){
    close_panel();
    next();
}

function open_panel(id){
    if(panel_is_open==0){
        // animations here
        last_open_panel=id;
        panel_is_open=1;
    }

    else if(panel_is_open==1){
        if(id!=last_open_panel){
            close_open_panel(function(){
                open_pannel(id);
            });
        }
    }
}

知道我在哪里误会吗? 感谢。

2 个答案:

答案 0 :(得分:1)

如果您正在使用jQuery特定解决方案,请查找Deferred Object

  在1.5版本中引入的jQuery.Deferred()是一个可链接的实用程序对象,它可以将多个回调注册到回调队列,调用回调队列,并中继任何同步或异步函数的成功或失败状态。

答案 1 :(得分:0)

您可以在函数中使用回调,例如

function open(callback)
{
   // do stuff
   callback(some_value);
}

然后你可以这样做:

open(function(value)
{
    // anything here will be executed
    // after the function has finished
});

callback()function(value)中的值是可选的,您可以返回一个简单的函数,而不是传递一个要回调的值,但是,它对某些需要异步的函数很有用。回调。

有关回调函数的更多信息:

相关问题