开发者

How do you remove and add then a class to two list elements on click

开发者 https://www.devze.com 2023-03-28 20:08 出处:网络
How do you remove and add a class to both the below lists simultaneously for the coresponding list item in order on click. eg click the 2nd list item and the change occurs on the second list item on t

How do you remove and add a class to both the below lists simultaneously for the coresponding list item in order on click. eg click the 2nd list item and the change occurs on the second list item on the other list

At the moment using the below I can only get this to happen on one of the li tags on any one click

$(document).ready(function() {

  $("ul.control li, ul.markers li").click(function() {
      $("ul.control li").removeClass("active"); 
      $(this).addClass("active");
      $("ul.markers li").removeClass("active"); 
      $(this).addClass("active"); 

});

Here is the markup for the two lists

<ul id="tabs" class="control">
    <li class="active"><a href="#tab1">Tab1</a></li>
    <li><a href="#tab2">Tab2</a></li>
    <li><a href="#tab3">Tab3</a></li>
    <li><a href="#tab4">Tab4</a></li>
</ul>


<ul id="tabs" class="markers">
  <li class="ac开发者_运维技巧tive">1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

Many thanks in advance for any help.


since jquery is kind enough to expose the index function, you could consider this:

$(document).ready(function() 
{    
    $("ul.control li, ul.markers li").click(function() 
    {
      var index = $(this).index();      
      $("ul.control li").removeClass("active"); 
      $("ul.markers li").removeClass("active"); 
      $("ul.control li:eq("+index+")").addClass('active');      
      $("ul.markers li:eq("+index+")").addClass('active');            
    });
}); 


First of all, IDs have to be unique. So in your case I would "convert" the id "tabs" to a CSS class.

But now to your question. That is how I would solve it:

$(function() {
    var lists = $(".control, .markers");

    lists.click(function(ev) {
        var el = (ev.srcElement.nodeName === "LI" ? ev.srcElement : ev.srcElement.parentNode);
        $(".active",lists).removeClass("active");
        $("li:eq(" + $(el).index() + ")", lists).addClass("active");
    });
});

example on jsfiddle.net


Much easier solution:

$(document).ready(function() {

  $("ul.control li, ul.markers li").click(function(e) {
     var that = $(this);
      that.siblings('.active').removeClass('active');
      that.addClass('active');
  });

});

Demo: http://jsfiddle.net/wesbos/mjmJH/2/

0

精彩评论

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