我将此特定脚本用于特定的展开/折叠项目,并决定我能够在同一页面上切换多个对象,但我不确定如何实现这一点。任何人都可以提供任何见解吗?
$('#faq_info_header').click(function() {
$('#faq_info_exp').toggle();
var arrow = $('#faq_info_header').find('.fa');
if (arrow.hasClass('fa-arrow-right')) {
arrow.removeClass('fa-arrow-right');
arrow.addClass('fa-arrow-down');
} else if (arrow.hasClass('fa-arrow-down')) {
arrow.removeClass('fa-arrow-down');
arrow.addClass('fa-arrow-right');
}
return false;
});
请求的HTML:
<a id="faq_info_header">This is the question? <i class="fa fa-arrow-right"></i></a>
<div id="faq_info_exp" style="display:none;">This is the hidden content</div>
答案 0 :(得分:2)
您可以将整个if语句替换为:
,可以使用toggleClass(此处为http://api.jquery.com/toggleClass/)arrow.toggleClass('fa-arrow-right fa-arrow-down');
好的,现在我想我理解了这个问题。这是fiddle
<强> HTML:强>
<div class="faqs">
<div class="faq_item">
<p>This is the question 1? <i class="fa fa-arrow-right"></i>
</p>
<div class="faq_info_exp">This is the hidden content 1</div>
</div>
<div class="faq_item">
<p>This is the question 2? <i class="fa fa-arrow-right"></i>
</p>
<div class="faq_info_exp">This is the hidden content 2</div>
</div>
<div class="faq_item">
<p>This is the question 3? <i class="fa fa-arrow-right"></i>
</p>
<div class="faq_info_exp">This is the hidden content 3</div>
</div>
</div>
JS:
$('.faqs').on('click', '.faq_item', function () {
$(this).children('.faq_info_exp').toggle();
$(this).find('i').toggleClass('fa-arrow-right fa-arrow-down');
});
<强> CSS:强>
.faq_info_exp {
display: none;
}
基本上我做的是:
$(this)
轻松引用它。$(this).children('.faq_info_exp').toggle();
找到带有faq_info_exp类的直接子元素并切换它。$(this).find('i').toggleClass('fa-arrow-right fa-arrow-down');
找到后代元素<i>
并切换该类。