2010-12-16 50 views
3

如何測試圖像是一組圖像中的第一個還是最後一個?如果一個div是第一個孩子,jQuery測試?

我試圖做一個和下一個按鈕在動畫或縮小取決於我是否在一系列圖像用下面的代碼的末尾:

var $current = jQuery("img .active"); 
var $next = $current.next(); 

if ($next != jQuery("img:first-child") 
{ 
// show next item and the previous button 
// seems to work? 

} else if ($next == jQuery("img:last-child") 
{ 
// hide the next button since we're at the end 
// doesn't seem to work?? 
} 
+0

什麼是id選擇器'#img'在做什麼?是否有一個ID爲'img'的元素保存圖像?或者應該只是簡單的'img'?另外,你的意思是'img.active',它將是'active'類的img元素嗎? – theazureshadow 2010-12-16 05:21:17

+0

對不起,這是一個錯字,我只是糾正它。 – redconservatory 2010-12-16 15:54:27

回答

8

你要檢查索引在IMG的:

var $current = jQuery("#img .active"), 
    index = $current.index(); 

if (index === 0) { 
    // This is the first 
} else if (index === jQuery("#img").children().length - 1) { 
    // This is the last 
} 
0

使用.each()假設沒有大的性能損失,我會做這樣的事情:

jQuery('#img').children().each(function(i,obj){ 
    // some code to show buttons 
    if (i <= 0) { // hide prev } 
    if (i >= $('#img').children().length - 1) { // hide next } 
}); 

然後隱藏所有$('#img').children(),除了活動的,或者您希望它起作用。

相關問題