循环遍历四个列表元素,应用“活动”类

时间:2010-04-06 05:08:17

标签: jquery

我想遍历四个都包含标签的li元素,将相应的类设置为“active”并删除“active”类。我在搞清楚如何通过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");
        }
    });
 });

任何帮助将不胜感激。三江源。

1 个答案:

答案 0 :(得分:4)

对我来说有点像矫枉过正:

$('#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)
  }      
});

与leftscroll的逻辑相同。请记住,你必须给一个 li元素页面上的“活动”类。