【问题标题】:jQuery test for if a div is the first child?jQuery测试一个div是否是第一个孩子?
【发布时间】:2011-05-26 08:23:03
【问题描述】:

如何测试一张图片是一组图片的第一张还是最后一张?

我正在尝试使用以下代码使上一个和下一个按钮动画化,具体取决于我是否位于一系列图像的末尾:

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

【问题讨论】:

  • id选择器#img在做什么?是否有 ID 为 img 的元素持有图像?还是应该只是简单的img?另外,您的意思是img.active,它是类active 的img 元素?
  • 抱歉打错了,我刚刚更正了。

标签: jquery conditional


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    假设使用 .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(),除了活动的$('#img').children(),或者你希望它起作用的任何方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多