简体   繁体   中英

Add class to several elements

I have a cloned element and I want it so if I add a class to one of them it checks for active removes is and adds it to this and translates to the other. Here's what I'm working with:

$(document).ready(function() {


    $("li").click(function(){

        /*Here I want to add something like var active = $(.clonedelement + this, this)
        but that does probably not makes sense, so what should i do? */

        var active = $(this)

      // If this isn't already active
      if (!$(this).hasClass("active")) {
        // Remove the class from anything that is active
        $("li.active").removeClass("active");
        // And make this active
        active.addClass("active");

      }
    });


});

Right now, it removes the current active from both, not does only add class to one.

I made a jsfiddle of it http://jsfiddle.net/pintu31/8BxuE/

function UpdateTableHeaders() {
   $(".persist-area").each(function() {

       var el             = $(this),
           offset         = el.offset(),
           scrollTop      = $(window).scrollTop(),
           Header = $("#headerny", this)

       if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
          Header.addClass("floatingHeader");
       } else {
          Header.removeClass("floatingHeader");

       };
   });
}
// DOM Ready      
$(function() {

   $(window)
    .scroll(UpdateTableHeaders)
    .trigger("scroll");

});

try this

demo updated 1
demo updated 2 //with clone(true)
demo updated 3 //with clone(false) - default
demo updated 4

 $(document).ready(function() {
    $(document).on('click', 'li', function(){
        var ind = $(this).index();
        $('li').removeClass('active');
        $('li').eq(ind).addClass('active');
        $('#header1').empty();
        $('#header').find('ul').clone(true).appendTo( '#header1' );
    });
});

If you just need to highlight the clicked element with the class of active, and remove all others then try this:

$("li").click(function(){
    $("li").removeClass("active");
    $(this).addClass("active");
  });

You don't really need to check if either this, or others already have the class, simply steamroller to 'active' class off all the others and add it to the one that's been clicked

$(document).ready(function() {


    $("li").click(function(){
        $("li").removeClass("active");
        // And make this active
        $(this).addClass("active");

      }
    });


});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM