Подтвердить что ты не робот

Как узнать, когда 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", который гласит: "Если нет оставшихся" следующих "элементов, тогда найдите первый.

Спасибо!

4b9b3361

Ответ 1

Определите .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') (если это позволяет разметка).

EDIT: Я исправил thisHeight, чтобы использовать элемент $next, на который мы ссылались.

Ответ 2

В качестве полезной ссылки, вы можете написать следующую функцию:

$.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();
};

Вместо:

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();;
}

Это будет:

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

Ссылка: http://www.mattvanandel.com/999/jquery-nextorfirst-function-guarantees-a-selection/

Ответ 3

согласно документации jquery, пустой объект jquery вернет .length 0.

так что вам нужно проверить возврат при вызове .next, а затем позвонить: сначала

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

Ответ 4

Вы можете использовать эти функции, чтобы узнать, является ли текущий элемент первым/последним.

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
{
    // ...
}