31

我正在使用 next() 函数显示一系列元素。一旦我到达终点,我想去第一个元素。有任何想法吗?

这是代码:

//Prev / Next Click
$('.nextSingle').click( function() {
    //Get the height of the next element
    var thisHeight = $(this).parent().parent().parent().next('.newsSingle').attr('rel');
    //Hide the current element
    $(this).parent().parent().parent()
        .animate({
            paddingBottom:'0px',
            top:'48px',
            height: '491px'
        }, 300) 
        //Get the next element and slide it in      
        .next('.newsSingle')
        .animate({
            top:'539px',
            height: thisHeight,
            paddingBottom:'100px'
        }, 300);
});

基本上我需要一个“if”语句,上面写着“如果没有剩余的‘下一个’元素,那么找到第一个。

谢谢!

4

4 回答 4

33

通过检查其属性.next()提前确定。length

$('.nextSingle').click( function() {
       // Cache the ancestor
    var $ancestor = $(this).parent().parent().parent();
       // Get the next .newsSingle
    var $next = $ancestor.next('.newsSingle');
       // If there wasn't a next one, go back to the first.
    if( $next.length == 0 ) {
        $next = $ancestor.prevAll('.newsSingle').last();;
    }

    //Get the height of the next element
    var thisHeight = $next.attr('rel');

    //Hide the current element
    $ancestor.animate({
            paddingBottom:'0px',
            top:'48px',
            height: '491px'
        }, 300);

        //Get the next element and slide it in      
    $next.animate({
            top:'539px',
            height: thisHeight,
            paddingBottom:'100px'
        }, 300);
});

顺便说一句,您可以替换.parent().parent().parent().closest('.newsSingle')(如果您的标记允许的话)。

编辑:我更正了thisHeight使用$next我们引用的元素。

于 2010-08-28T17:48:16.663 回答
22

As a useful reference, the following is a function you can write and include:

$.fn.nextOrFirst = function(selector)
{
  var next = this.next(selector);
  return (next.length) ? next : this.prevAll(selector).last();
};

$.fn.prevOrLast = function(selector)
{
  var prev = this.prev(selector);
  return (prev.length) ? prev : this.nextAll(selector).last();
};

Instead of:

var $next = $ancestor.next('.newsSingle');
   // If there wasn't a next one, go back to the first.
if( $next.length == 0 ) {
    $next = $ancestor.prevAll('.newsSingle').last();;
}

It would be:

$next = $ancestor.nextOrFirst('.newsSingle');

Reference: http://www.mattvanandel.com/999/jquery-nextorfirst-function-guarantees-a-selection/

于 2013-04-11T22:18:57.553 回答
6

根据 jquery 文档,一个空的 jquery 对象将返回 .length 0。

所以你需要做的是在调用 .next 时检查返回,然后调用 :first

http://api.jquery.com/next/

于 2010-08-28T17:46:32.933 回答
1

您可以使用这些函数来查看当前项目是否是第一个/最后一个孩子。

jQuery.fn.isFirst = function() { return (this[0] === this.parent().children().first()[0]); };
jQuery.fn.isLast = function() { return (this[0] === this.parent().children().last()[0]); };

if($ancestor.isLast())
{
    // ...
}
else
{
    // ...
}
于 2015-11-10T10:53:18.697 回答