开发者

cycle through four list elements, applying an "active" class

开发者 https://www.devze.com 2022-12-25 14:00 出处:网络
I would like to cycle through four li elements that all containtags, setting the appropriateclass to \"active\" and remove the\"active\" class.I\'m having a bit of trouble figuring out how to achieve

I would like to cycle through four li elements that all contain tags, setting the appropriate class to "active" and remove the "active" class. I'm having a bit of trouble figuring out how to achieve this via jQuery. HTML:

<ul class="liveMenu">
 <li id="leftScroll"></li>
 <li id="liveButton_1"><a class="buttons" href="#featured_1"></a></li>
 <li id="liveButton_2"><a class="buttons" href="#featured_2"></a></li>
 <li id="liveButton开发者_如何学编程_3"><a class="buttons" href="#featured_3"></a></li>
 <li id="liveButton_4"><a class="buttons" href="#featured_4"></a></li>
 <li id="rightScroll"></li>
</ul>

jquery:

var index = 0;
$("#rightScroll").click(function(){

 if(index != 3){
  index++;
 } else {
  index = 0;
 }
    //this part is untested, it should work though
    $("a.active").removeClass("active");
 //this is where I am getting hung up
    //I need something like...

    $.each("li.buttons", function(i){
        if(i == index){
            $(this).addClass("active");
        }
    });

 });

$("#leftScroll").click(function(){
 if(index != 0){
  index--;
 } else {
  index = 3;
 }

    $.each("li.items", function(i){
        if(i == index){
            $(this).addClass("active");
        }
    });
 });

any help would be greatly appreciated. Thankyou.


Looks a little bit like overkill to me:

$('#rightscroll').bind('click', function(e){
  var next = $(this).next('li');

  if(next){
     $('.active').removeClass('active');
     next.addClass('active');         
  }
  else{
     // maybe select first li element here (index 0)
  }      
});

and the same logic for the leftscroll. Keep in mind, that you have to give one li element the class 'active' on page ready.

0

精彩评论

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