2009-08-26 43 views
0

例如,我使用$ .ajax函數中的beforeSend選項。在下面的代碼示例中,.html函數將在執行淡出之前執行語句。我怎麼能阻止這種行爲?jQuery - 如何在以前的語句完成後才使語句執行?

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

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

所以會發生什麼是期間淡出,jQuery將注入HTML「成功」。我希望它在動畫完成後發生。

我應該怎麼辦?

謝謝!

回答

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"); 
}); 
+0

我不確定'$(this)'是否在回調中工作。您可能需要重新查詢。 – 2009-08-26 13:31:38

+2

@Josh Stodola - $(this)實際上是指#container,不需要重新查詢 – karim79 2009-08-26 13:32:49

+0

但是我想讓div的內容淡入。我希望能夠在div不可見時更改類和div內容。明白我的意思了嗎? – Jeff 2009-08-26 13:33:20

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(); 
       } 
}); 
相關問題