如何找出 next() 何时到达末尾,然后转到第一项 [英] How to find out when next() reaches the end, then go to the first item

查看:28
本文介绍了如何找出 next() 何时到达末尾,然后转到第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 next() 函数显示一系列元素.但是,一旦我到达终点,我就想去第一个元素.有什么想法吗?

I am displaying a series of elements using the next() function. Once I reach the end though, I want to go to the first element. Any ideas?

代码如下:

//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"语句,表示如果没有剩余的‘下一个’元素,则找到第一个.

Basically I need an "if" statement that says "if there are no remaining 'next' elements, then find the first one.

谢谢!

推荐答案

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

Determine the .next() ahead of time by checking its length property.

$('.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') (如果您的标记允许它).

By the way, you could replace .parent().parent().parent() with .closest('.newsSingle') (if your markup allows it).

我更正了 thisHeight 以使用我们引用的 $next 元素.

I corrected the thisHeight to use the $next element that we referenced.

这篇关于如何找出 next() 何时到达末尾,然后转到第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆