2013-12-10 36 views
0

我有这个简单的next和previous功能,但是我写了一个简单的问题。在最后一个滑块上点击下一个滑块,它会显示一个空白滑块,然后点击下一个滑块,它将按照它的设想从头开始。我错过了什么?下面是jQuery代码;Jquery Next和Prev Button循环功能

$('div.contsliders').each(function(e) { 
    if (e != 0) 
     $(this).hide(); 
    }); 

$('span.next').click(function(){ 
    if ($('div.contsliders:visible').next().length != 0) 
     $('div.contsliders:visible').next().fadeIn(1000).prev().hide(); 

    else { 
     $('div.contsliders:visible').hide(); 
     $('div.contsliders:first').fadeIn(1000); 
    } 
    return false; 
}); 

$('span.prev').click(function(){ 
    if ($('div.contsliders:visible').prev().length != 0) 
     $('div.contsliders:visible').prev().fadeIn(1000).next().hide(); 
    else { 
     $('div.contsliders:visible').hide(); 
     $('div.contsliders:last').fadeIn(1000); 
    } 
    return false; 
}); 

HERE IS THE JSFIDDLE LINK

我真的很感激队友,谢谢。

回答

1

这是因为当它检查以下条件为在div你认为它是最后使用$('div.contsliders:visible').next().length给出​​(因此长度仍然是1而不是0作为假定),所以它显示了一个,而不是移动到一开始,当你再次点击它时会发生这种情况。这是因为​​是最后一张幻灯片#five旁边的div。

if ($('div.contsliders:visible').next().length != 0) 
    $('div.contsliders:visible').next().fadeIn(1000).prev().hide(); 

你可以把它改成:

var $nxt = $('div.contsliders:visible').next('.contsliders'); 
    if ($nxt.length != 0) 
     $nxt.fadeIn(1000).prev().hide(); 

Demo

逸岸可以简化这只是一个处理程序,以及:

$('div.contsliders:gt(0)').hide(); //Hide all but the first one 

var $allSlides = $('div.contsliders'), 
    traverseDefault = "first", //set the defaults 
    actionDefault ="next"; 

$('span.next, span.prev').click(function(){ 

    var traverse = traverseDefault, 
     action = actionDefault; 

    if($(this).is('.prev')){ //if action is prev 
     traverse = "last"; //set traverse to last in case nothing is available 
     action = "prev"; //set action to prev 
    } 

    var $curr = $allSlides.filter(':visible'), //get the visible slide 
     $nxtTarget = $curr[action](".contsliders"); //get the next target based on the action. 

    $curr.stop(true, true).fadeIn(1000).hide(); //hide current one 

    if (!$nxtTarget.length){ //if no next 
     $nxtTarget = $allSlides[traverse](); //based on traverse pick the next one 
    } 

    $nxtTarget.stop(true, true).fadeIn(1000); //show the target 

}); 

Demo

+0

哈哈,谢谢你。这完全合理。猜猜我太淹没了代码,我看着那个。感谢一堆救了我一些时间,赞赏。 –

+0

@ JoeyNg'ethe欢迎您访问我的更新。 – PSL

+0

谢谢你,这更好,谢谢你的时间。 –