jQuery: как узнать, когда next () достигнет конца, а затем перейти к первому элементу - PullRequest
28 голосов
/ 28 августа 2010

Я отображаю серию элементов, используя функцию 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);
});

В основном мне нужно выражение «если», которое говорит «если нет оставшихся« следующих »элементов, то найдите первый.1006 *

Спасибо!

Ответы [ 4 ]

31 голосов
/ 28 августа 2010

Определите .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, на который мы ссылались.

19 голосов
/ 12 апреля 2013

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

$.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/

6 голосов
/ 28 августа 2010

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

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

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

1 голос
/ 10 ноября 2015

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

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