如果一个div是第一个孩子,jQuery测试?

问题描述:

如何测试图像是一组图像中的第一个还是最后一个?如果一个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

你要检查索引在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 
} 

使用.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(),除了活动的,或者您希望它起作用。