简体   繁体   English

如何在JavaScript中删除/添加多个类

[英]How to remove/add more than one class in Javascript

I have a slider and when I click on nav buttons, I want to put the class "active" on one element and "active2" on another one. 我有一个滑块,当我单击导航按钮时,我想将类“ active”放在一个元素上,将“ active2”放在另一个元素上。 Here's the code I have... It's not working. 这是我的代码...不起作用。 It works on first slide, which leads me to believe the class is not being added to other slide on click. 它可以在第一张幻灯片上使用,这使我相信该课程不会在单击时添加到其他幻灯片上。

<script type="text/javascript">
   $(document).ready(function(){
       $('input[name="slider"]').click(function(event){
           $('.top').removeClass('active');
           $('.bkg').removeClass('active2');
           $('.slider-wrapper').find('div').eq($(this).index()).find('.top').addClass('active');
           $('.slider-wrapper').find('div').eq($(this).index()).find('.bkg').addClass('active2');

       });
    });
</script>

HTML: HTML:

<div class="wrapper">
 <input checked type=radio name="slider" id="slide1" />
  <input type=radio name="slider" id="slide2" />

  <div class="slider-wrapper">
  <div class="inner">
      <section>

<div class="top active">
            <img src="images/test.png">

        </div>
        <div class="bkg">
           <a class="active2">hello</a>
                    <img class="bkg-image" src="images/test.jpg">
        <div class="overlay"></div>

        </div>
  </section>
  <section>
    <div class="top">
      <img src="images/test.png">
    </div>
    <div class="bkg">
      <a class="active2">hello</a>
        <img class="bkg-image" src="images/test.jpg">
      <div class="overlay"></div>
    </div>
  </section>

  </div>
  <!-- .inner -->
</div>
<!-- .slider-wrapper -->
<div class="slider-dot-control">
  <label for=slide1></label>
  <label for=slide2></label>

</div>

</div>
</article>

The find('div') was finding all divs under slider-wrapper, not just the top level ones. find('div')正在滑块包装下查找所有div,而不仅仅是顶层的。 That resulted in the later chained selectors to not work the way you wanted. 这导致后来的链式选择器无法按您想要的方式工作。

If you switch the find to .top and .bkg then the eq selector seems to work as intended. 如果将查找结果切换为.top和.bkg,则eq选择器似乎可以正常工作。

   $(document).ready(function(){
       $('input[name="slider"]').click(function(event){
           $('.top').removeClass('active');
           $('.bkg').removeClass('active2');
           $('.slider-wrapper').find('.top').eq($(this).index()).addClass('active');
           $('.slider-wrapper').find('.bkg').eq($(this).index()).addClass('active2');           
       });
    });

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

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