手风琴打开/关闭div

时间:2013-10-15 16:34:12

标签: jquery accordion

我正在设置一个手风琴,一旦点击h3(无论有多少),都需要打开/关闭类side-nav-block-item中的所有div。我无法修改结构HTML,只添加类。

HTML结构:

<div class="side-nav">

<div class="side-nav-item">
<h3>Title</h3>
<div class="side-nav-block-item">content</div>
<div class="side-nav-block-item">content</div>
</div>

<div class="side-nav-item">
<h3>Title</h3>
<div class="side-nav-block-item">content</div>
</div>

</div>

Jquery(我失败的尝试)

    $('.side-nav h3').addClass('on');
//ACCORDION BUTTON ACTION (ON CLICK DO THE FOLLOWING)
$('.side-nav h3').click(function() {

    //REMOVE THE ON CLASS FROM ALL BUTTONS
    $('.side-nav h3').removeClass('on');

    //NO MATTER WHAT WE CLOSE ALL OPEN SLIDES
    $('.side-nav-block-item').slideUp('normal');

    //IF THE NEXT SLIDE WASN'T OPEN THEN OPEN IT
    if($(this).next().is(':hidden') == true) {

        //ADD THE ON CLASS TO THE BUTTON
        $(this).next().addClass('on');

        //OPEN THE SLIDE
        $(this).next().slideDown('normal');
     } 


 });

1 个答案:

答案 0 :(得分:1)

如果我理解正确,则无需检查下一个标头是否隐藏,只需检查.side-nav h3是否有类.on。如果是,请删除课程slideUp。如果没有,请添加课程slideDown

看看这个jsFiddle。它应该完成你想要的。

$('.side-nav h3').addClass('on');
$('.side-nav h3').click(function() {
    if ($(this).hasClass('on')) {
        // Remove class
        $(this).toggleClass('on');
        // Slide up the siblings of the header that was clicked
        $(this).siblings('.side-nav-block-item').slideUp('normal');
    } else {
        // Add class
        $(this).toggleClass('on');
        // Slide down the siblings of the header that was clicked
        $(this).siblings('.side-nav-block-item').slideDown('normal');
    }
});

<强>更新

以下是更新的jsFiddle