jquery - 如何找出 next() 何时到达末尾,然后转到第一项

标签 jquery jquery-selectors

我正在使用 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',
            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 元素。

关于jquery - 如何找出 next() 何时到达末尾,然后转到第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3591755/

相关文章:

jquery 数据选择器

jquery选择具有attr值的tbody

javascript - jquery 只克隆元素的内容

javascript - 尝试通过 npm 加载 jQuery 插件

javascript - 在 fullpage.js Slideload 回调中获取已加载的幻灯片

javascript - 从文本框数组中选择一个文本框

javascript - 我如何知道数据表中是否选择了任何行?

java - 如果在 html div 中调整图像大小,如何获取原始图像裁剪选择器?

javascript - 如何在不知道第一个元素是什么标签的情况下获取它?

Jquery的removeClass方法