2010-07-27 23 views
1

我有以下列表:如何讓jQuery在完成之前將一個效果應用於.each()循環中的每個項目?

<div id="test">test</div> 

<ul> 
    <li>foo</li> 
    <li>bar</li> 
    <li>sta</li> 
    <li>cko</li> 
</ul> 

和下面的jQuery代碼:

$(document).ready(function() { 
    $('li').each(function(index) { 
     $('#test').text($(this).text()); 
     $('#test').show("drop", { direction: "down" }, 500, function() { 
      $("#test").delay(1000).hide("puff", {}, 100); 
     }); 
    }); 
}); 

從邏輯上講,這應該改變div的內容testfoo,應用降和粉撲的效果,變化內容爲bar,應用效果等。但是當你運行它時,整個.each循環會在效果開始前完成,所以最後一個元素cko首先出現並獲得4次動畫。

我怎樣才能讓每個項目得到的效果,然後移動到下一個?

回答

2

您需要添加的第一個函數隊列,以及如果你希望它在隊列的順序發生,(使用.queue()),像這樣:

$(function() { 
    $('li').each(function(index) { 
     var li = $(this); 
     $('#test').queue(function(n) { 
      $(this).text(li.text());   //set the text 
      n();        //call next function in the queue 
     }).show("drop", { direction: "down" }, 500, function() { 
      $(this).delay(1000).hide("puff", {}, 100); 
     }); 
    }); 
});​ 

You can give it a try here。這會使文本設置按順序與動畫一起發生,這似乎是您所追求的。調用傳遞給你的隊列回調的函數是很重要的,因爲它是推進隊列的動作,在這種情況下觸發後面的動畫。

.delay()將有一個奇怪的效果,你擁有它,以及,如果你想在隊列的方式,像這樣做:

$(function() { 
    $('li').each(function(index) { 
     var li = $(this); 
     $('#test').queue(function(n) { 
      $(this).text(li.text()); 
      n(); 
     }).show("drop", { direction: "down" }, 500) 
      .delay(1000).hide("puff", {}, 100); 
    }); 
});​ 

You can try it here,這實際上停頓一秒鐘的每個元素繼續前進。

+0

這幾乎工作,但我需要的粉撲動畫緊跟在下降動畫。現在,所有物品都會一個接一個地滑出來,最後一起膨脹。讓我們在你給的鏈接上擺弄它... – aalaap 2010-07-27 14:15:45

0

沒有測試,但我認爲你可以嘗試:

$(document).ready(function() { 
    animateItem($('li'), 0); 
}); 

function animateItem(li, i) { 
    if (li.length > i) { 
     $('#test').text(li.eq(i).text()); 
     $('#test').show("drop", { direction: "down" }, 500, function() { 
      $("#test").delay(1000).hide("puff", {}, 100, function() { 
       animateItem(li, i++); 
      }); 
     }); 
    } 
} 
相關問題