【问题标题】:Adding And Removing Class on Active Accordion Toggle Element在 Active Accordion Toggle 元素上添加和删除类
【发布时间】:2019-04-28 00:54:08
【问题描述】:

我有一个手风琴的 Jquery 代码,它运行良好,除了我需要在活动触发器上添加/删除类。我的意思是,当点击 H2 元素时,我需要添加一个“手风琴切换”类。此处显示的代码在切换时将类添加到所有 H2 元素,我只需要将其添加到活动 H2。

我可以在这方面寻求帮助。

$(document).ready(function(){
   $('div.accordion-content> p').hide();  
   $('div.accordion-content> h2').click(function() {
     $(this).next('p').slideToggle('fast')
     .siblings('p:visible').slideUp('fast');
     $('div.accordion-content> h2').toggleClass('accordion-toggled');
   });
});

HTML

<div class="accordion-content">
   <h2>Question 1</h2>
   <p>Some answers for question 1</p>
   <h2>Question 2</h2>
   <p>Some answers for question 2</p>
   <h2>Question 3</h2>
   <p>Some answers for question 3</p>
</div>

【问题讨论】:

    标签: jquery accordion slidetoggle


    【解决方案1】:

    通过使用this 关键字,您可以引用刚刚单击的元素:

    $(document).ready(function(){
       $('div.accordion-content> p').hide();  
       $('div.accordion-content> h2').click(function() {
         $(this).next('p').slideToggle('fast')
         .siblings('p:visible').slideUp('fast');
          $(this).toggleClass('accordion-toggled');
          $('div.accordion-content> h2').not(this).removeClass('accordion-toggled');
       });
    });
    .accordion-toggled{
      color: red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="accordion-content">
       <h2>Question 1</h2>
       <p>Some answers for question 1</p>
       <h2>Question 2</h2>
       <p>Some answers for question 2</p>
       <h2>Question 3</h2>
       <p>Some answers for question 3</p>
    </div>

    【讨论】:

    • 它已经足够接近我想要的了。但是,如果您运行您提供的代码,您会注意到单击任何 H2 元素将添加一个类和样式(红色),但再次单击它不会删除该类。这意味着它隐藏了答案(向上切换),但该 h2 元素的红色仍然存在。它应该基于点击添加和删除类。感谢您的贡献。
    • @Delinx 你是对的,改变了类处理的顺序并从removeClass选择器中排除了当前元素
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    相关资源
    最近更新 更多