jQuery:如何找到next()到达结束,然后转到第一个项目

前端之家收集整理的这篇文章主要介绍了jQuery:如何找到next()到达结束,然后转到第一个项目前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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”语句,说“如果没有剩余的”下一个“元素,那么找到第一个。

谢谢!

解决方法

通过检查它的length属性来提前确定.next()。
$('.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',300);

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

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

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

原文链接:https://www.f2er.com/jquery/183360.html

猜你在找的jQuery相关文章