我有一个用于手风琴的 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>
通过使用 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>