在活动手风琴切换元素上添加和删除 Class
Adding And Removing Class on Active Accordion Toggle Element
我有一个 Jquery 手风琴代码,它运行良好,除了我需要 add/remove class 在活动触发器上。我的意思是,当单击 H2 元素时,我需要向其添加 class "accordion-toggled"。此处显示的代码在切换时将 class 添加到所有 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>
我有一个 Jquery 手风琴代码,它运行良好,除了我需要 add/remove class 在活动触发器上。我的意思是,当单击 H2 元素时,我需要向其添加 class "accordion-toggled"。此处显示的代码在切换时将 class 添加到所有 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>