简体   繁体   English

将类添加到多个元素

[英]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/ 我做了一个jsfiddle它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 演示更新1
demo updated 2 //with clone(true) 演示更新2 //使用clone(true)
demo updated 3 //with clone(false) - default demo更新3 //使用clone(false) - 默认
demo updated 4 演示更新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");

      }
    });


});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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