2013-04-15 39 views
1

我有一些代碼試圖在延遲之後依次顯示和隱藏div。如何在JQuery中顯示/隱藏div延遲

$('#box1').delay(1800).hide('slow'); 
delay(1800).$('#box2').delay(1800).show('slow'); 
delay(1800).$('#box2').delay(1800).hide('slow'); 
delay(1800).$('#box3').delay(1800).show('slow'); 
delay(1800).$('#box3').delay(1800).hide('slow'); 
delay(1800).$('#box4').delay(1800).show('slow'); 
delay(1800).$('#box4').delay(1800).hide('slow'); 
delay(1800).$('#box1').delay(1800).show('slow'); 

該div不顯示和隱藏。如何在延遲後讓div顯示和隱藏?

+6

'delay(1800)。$'語法無效。刪除那個地方的「延遲(1800)」部分。 –

+0

但是,即使我刪除它仍然無法正常工作 這個想法是每個盒子都是另一個隱藏的 –

+0

沒錯,它並不意味着是一個解決方案,它只是用來修復即時語法錯誤,否則會導致您的代碼根本無法工作,而不考慮它包含的邏輯錯誤。 –

回答

0

用戶Kevin B在評論中提出以下建議。這需要照顧我的原始答案迎合的厄運的詳細性質/金字塔。

$('#box1').delay(1800).hide('slow').promise().then(function(){ 
    return $('#box2').delay(1800).show('slow').promise(); 
}).then(function(){ 
    return $('#box2').delay(1800).hide('slow').promise(); 
}).then(function(){ 
    return $('#box3').delay(1800).show('slow').promise(); 
}).then(function(){ 
    return $('#box3').delay(1800).hide('slow').promise(); 
}).then(function(){ 
    return $('#box4').delay(1800).show('slow').promise(); 
}).then(function(){ 
    return $('#box4').delay(1800).hide('slow').promise(); 
}).then(function(){ 
    return $('#box1').delay(1800).show('slow').promise(); 
}); 
+1

使用諾言對象可以使它看起來更清新一些(沒有末日金字塔):http://jsfiddle.net/uXNjK/1/ –

+0

凱文,那太棒了。非常感謝您向我展示這一點。我會在你的答案中包含你的建議。 –

+0

是否有可能整個事情循環,是否有一個goto函數在jQuery或一些1 = 1? –

1

也許東西沿着這個線條更會更好:

// Go over each .box in the collection 
$(".box").each(function (i) { 
    $(this) 
     // Show after index * 1800 (0 * 1800, 1 * 1800, 2 * 1800, etc) 
     .delay(i * 1800).show("slow") 
     // Hide after same calculation 
     .delay(i * 1800).hide("slow"); 
}); 

只要給每個箱子的.box類。