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

时间:2010-12-16 05:04:38

标签: jquery conditional

如果图像是一组图像的第一个或最后一个,如何测试?

我试图让上一个和下一个按钮动画显示或取出,具体取决于我是否在一系列图像的末尾使用以下代码:

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??
}

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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()之外的所有{{1}},或者您希望它能够正常运行。

相关问题