2010-08-28 48 views
25

Estoy mostrando una serie de elementos usando la función next(). Una vez que llego al final, quiero ir al primer elemento. ¿Algunas ideas?jQuery: cómo saber cuándo next() llega al final, luego vaya al primer elemento

Aquí está el código:.

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

Básicamente necesito un "if" que dice "si no hay elementos restantes 'siguiente', y luego encontrar el primero

Gracias

!

Respuesta

27

Determine la .next() antes de tiempo mediante la comprobación de su propiedad 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); 
}); 

Por cierto, podría reemplazar .parent().parent().parent() con .closest('.newsSingle') (si su margen de beneficio lo permite).

EDIT: corregí el thisHeight usar el elemento $next que se hace referencia.

+0

thx patrick! Parece prometedor, pero me aparece "Error: $ ancestor.prevAll (". NewsSingle "). La última no es una función" –

+0

@ j-man86 - ¿Qué versión de jQuery estás usando? El método '.last()' se agregó en jQuery 1.4. – user113716

+1

@ j-man86 - Estaba a punto de hacer una edición. Dejaré un comentario en su lugar. Si necesita una versión anterior de jQuery, en lugar de 'prevAll(). Last()', podría hacer '.prevAll (': last')'. – user113716

4

según la documentación de jquery, un objeto jquery vacío devolverá .length 0.

así que lo que necesita hacer es comprobar la devolución cuando llame .next, a nd entonces llaman: primero

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

+0

genial ... ¿cómo hago esto? –

15

Como referencia, la siguiente es una función que puede escribir e incluyen:

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

En lugar de:

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

Sería:

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

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

+0

Este es, de lejos, el método más simple y directo. ¡Gracias! – Aziz

+0

Funciona muy bien. Puede ser 'this.siblings (selector) .first()' y 'last()' – Miro

1

Puede usar estas funciones para ver si el elemento actual es el primer/último hijo.

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