开发者

jQuery looping prev next

I found this bit of code whist searching for a basic slider and its near enough does what I want but I would like it to loop once it got to the last li, i.e if last li and next button is clicked loop to 1st and continue,

all help is appreciated and as always thanks in advance.

$('.udtalelse').addClass("passiv");
ctrlKunder(0);

$('#prev').click(function() {
    var index = getActive();
    if (index == 0) return;
    index--;
    ctrlKunder(index);
})
$('#next').click(function() {
    var index = getActive();
    if (index == $('.udtalelse').length - 1) return;
    index++;
    ctrlKunder(index);
})

function ctrlKunder(ele) {
    $('.udtalelse').removeClass("active").addClass("passiv");
    $('.udtalelse').eq(ele开发者_如何转开发).removeClass("passiv").addClass("active");
}

function getActive() {
    var index;
    $('.udtalelse').each(function(i) {
        if ($(this).hasClass("active")) index = i;
    })
    return index;
}

<ul class="kunder">
    <li><span class="udtalelse">Indhold 1</span></li>
    <li><span class="udtalelse">Indhold 2</span></li>
    <li><span class="udtalelse">Indhold 3</span></li>
</ul>
<span class="kunderpagination">
    <a href="#" id="prev">« Previous</a> |
    <a href="#" id="next">Next »</a>
</span>


Your code can be greatly simplified like this:

var all = $('.udtalelse').addClass("passiv");

var i = -1;

$('#prev').click(function() {
    ctrlKunder( i = !i ? all.length - 1 : --i );
});
$('#next').click(function() {
    ctrlKunder( i = ++i % all.length );
}).click();

function ctrlKunder(ele) {
    all.removeClass("active").addClass("passiv");
    all.eq(ele).removeClass("passiv").addClass("active");
}

Also more efficient because the .udtalelse elements are cached.

Example: http://jsfiddle.net/3z9uc/


EDIT: I forgot to update the answer with the revision that's in the fiddle. Fixed.


Change this to:

        $('#next').click(function(){
            var index = getActive();
            if(index == $('.udtalelse').length - 1) { 
                index = 0; 
            } else { 
                index++;
            }
            ctrlKunder(index);

And if you want the same wrap on previous:

        $('#prev').click(function(){
            var index = getActive();
            if(index == 0) {
                $index = $('.udtalelse').length - 1;
            } else {
                index--;
            }
            ctrlKunder(index);
        }) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜