Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

javascript - How to create simple next and prev trigger button for slider's pagination buttons?

I am trying to carry a class between li's with combine each() and eq() methods when buttons clicked. I am using same code with previous and next buttons except i+1 and i-1 but it is returning me different problems.

Here is jsFiddle to examine.

html:

<span class="prev">prev</span>
<ul>
    <li>0</li>
    <li>1</li>
    <li class="active">2</li>
    <li>3</li>
    <li>4</li>
</ul>
<span class="next">next</span>

jQuery:

var li = $('li');

$('.prev').click(function() {
    li.each(function(i) {
        if ( $(this).hasClass('active') ) {
            console.log(i);
            //this returning current true value = 2

            li.removeClass('active');
            li.eq(i-1).addClass('active');
            //this is working better
            //problem is: not selecting 4
        }
    });
});

$('.next').click(function() {
    li.each(function(i) {
        if ( $(this).hasClass('active') ) {
            console.log(i);
            //this returning current true value = 2

            //problem starts:
            //li.removeClass('active');
            //when this is active; all active classes are gone

            li.eq(i+1).addClass('active');
            //try to select next 'li' here
            //but it is selecting all li's bigger than current value
        }
    });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'd try using something more like:

Here is working jsFiddle.

$(".next").click(function(){
    if($("li.active").next().length > 0){
        $("li.active").removeClass("active").next("li").addClass("active");
    }
});
$(".prev").click(function(){
    if($("li.active").prev().length > 0){
        $("li.active").removeClass("active").prev("li").addClass("active");
    }
});?

using the 'next' selector: Jquery Next

I avoid math when possible. Counting is hard :-). That said I'm thinking your problem above may be with the index. Hard to say. I'd avoid using selectors like "li" when dealing with a list like this. Try putting a class on the 'ul' portion of it and addressing your li's as: ".myList li"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...