在子元素上切换类(并删除兄弟元素)

时间:2017-04-26 20:22:46

标签: javascript jquery

我有以下代码,用于通过切换.active类来创建手风琴效果。点击.section-header后,我在标题和.section-content上切换了一个类。这很有效。

然而,如上所述,这是为了创建一个手风琴效果,它是多个.accordion-section <div>标签。我需要调整jquery,以便除了当前活动的.active之外的所有.accordion-section类。目前,点击.section-header可在所有.active .section-content个标签上切换<div>课程。

感谢。

HTML

<div class="accordion-section">
    <a class="section-header">
        <h3>Title</h3>
    </a>
    <div class="section-content">
        <div>Content</div>
    </div>
</div>

JS

$('.accordion-section .section-header').click(function(){
    $(this).toggleClass('active');
    $(this).siblings().toggleClass('active');
});

1 个答案:

答案 0 :(得分:1)

$('.accordion-section .section-header').click(function(){
    // Check to see the initial state of the element
    var isActive = $(this).hasClass('active');

    // first remove the active class from all other section headers within this accordion section
    $('.accordion-section')
        .find('.section-header, .section-content')
            .removeClass('active');

    // Get the header and content for this section
    var sectionHeaderAndContent = $(this)
        .closest('.accordion-section')
            .find('.section-header, .section-content');

    // Toggle Active State: Set final active state based on state when clicked
    (isActive) ? sectionHeaderAndContent.removeClass('active'): sectionHeaderAndContent.addClass('active');
});
相关问题