jQuery - 如何在前一个语句完成后才能执行语句?

时间:2009-08-26 13:26:37

标签: jquery

例如,我在$ .ajax函数中使用beforeSend选项。在下面的代码示例中,.html函数将在之前的语句中发生淡出时执行。我怎么能阻止这种行为?

 jQuery("#container").fadeOut("slow", function() {
     jQuery("#container").removeClass('error');
 });

 jQuery("#container").html("success").fadeIn("slow");

那么在淡出期间会发生什么,jquery会注入html“成功”。我希望它在动画完成后发生。

我该怎么办呢?

谢谢!

3 个答案:

答案 0 :(得分:5)

使用回调...

jQuery("#container").fadeOut("slow", function() {
  // At this point, animation is complete, and the element is invisible
  jQuery(this).removeClass("error").html("success").fadeIn("slow");
});

答案 1 :(得分:0)

答案 2 :(得分:0)

如果你在ajax调用的上下文中使用它,那么我希望后面的代码成为你成功回调的一部分,而不是内容与容器的淡入淡出。这将使容器在调用之前隐藏,并且仅在调用成功返回后显示它。您可能实际上想要将其拆分,以便fadeIn在完成时发生,这样您无论呼叫是否成功都可以执行此操作。

jQuery.ajax({
   ...
   beforeSend: function() {
                   jQuery("#container").fadeOut("slow", function() {
                       jQuery("#container").removeClass('error'); }
                   });
               },
   success:    function(data) {
                   jQuery("#container").html("success").fadeIn("slow");
               }
   ...
});


jQuery.ajax({
   ...
   beforeSend: function() {
                   jQuery("#container").fadeOut("slow", function() {
                       jQuery("#container").removeClass('error'); }
                   });
               },
   success:    function(data) {
                   jQuery("#container").html("success");
               },
   error:      function(req,status) {
                   jQuery("#container").html("error").addClass("error");
               },
   complete:   function() {
                   jQuery("#container").fadeIn();
               }
});