我有一个手风琴的Jquery代码,它运行良好,除了我需要在主动触发器上添加/删除类。我的意思是,当点击H2元素时,我需要添加一个“accordion-toggled”类。这里显示的代码在切换时将类添加到所有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>
使用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>