我正在使用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);
});
Run Code Online (Sandbox Code Playgroud)
基本上我需要一个"if"语句,说"如果没有剩下的'下一个'元素,那么找到第一个元素.
谢谢!
use*_*716 31
.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);
});
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你可以替换.parent().parent().parent()使用.closest('.newsSingle')(如果您的标记允许的话).
编辑:我更正了thisHeight使用$next我们引用的元素.
luc*_*uma 20
作为一个有用的参考,以下是您可以编写的功能,包括:
$.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();
};
Run Code Online (Sandbox Code Playgroud)
代替:
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();;
}
Run Code Online (Sandbox Code Playgroud)
这将是:
$next = $ancestor.nextOrFirst('.newsSingle');
Run Code Online (Sandbox Code Playgroud)
参考:http: //www.mattvanandel.com/999/jquery-nextorfirst-function-guarantees-a-selection/
根据jquery文档,空的jquery对象将返回.length 0.
所以你需要做的是在你调用.next时检查返回,然后调用:first