Jquery accordion menu (3 level) How to?

2019-08-03 18:45发布

问题:

I have this jquery code:

$(document).ready(function(){
$("#accordion2 h3").click(function(){
    //slide up all the link lists
    $("#accordion2 ul ul").slideUp();
    //slide down the link list below the h3 clicked - only if its closed
    if(!$(this).next().is(":visible"))
    {
        $(this).next().slideDown();
    }
})
})

And HTML:

<div id="accordion2">
<ul>
    <li>
        <h3>Articles</h3>
        <ul>
            <li><a href="#">Nature</a>
            <ul>
              <li>Wild life</li>
              <li>Flowers</li>
              <li>Animals</li>
            </ul>
            </li>
            <li><a href="#">Earth</a></li>
            <li><a href="#">Space</a></li>
            <li><a href="#">Ocean</a></li>
            <li><a href="#">Land</a></li>
        </ul>
    </li>
</ul>
</div>

How do i modify the jQuery code so that the user can slidedown the "Nature" and its contents? 3 third level menu.

回答1:

I'm guessing this is what you are after? If not, then please clarify your question.

$(document).ready(function(){
    $("#accordion2 h3").click(function(){
        $(this).next().slideToggle();
    })
     $("#accordion2 ul ul li a").click(function(){
        $(this).next().slideToggle();
    })
})

Working demo



回答2:

Multi level Accordion: JSFiddle

HTML

<ul id="menu" class="menu">
<li><a href="#">Sub item A</a>
    <ul class="sub-menu">
        <li><a href="#">Sub Sub item A</a>
            <ul class="sub-menu">
                <li><a href="#">sub sub sub item a</a>
                <ul class="sub-menu">
            <li>sub sub sub sub item a</li>
            <li>sub sub sub sub item b</li>
                    </ul>
                </li>
            <li>sub sub sub item b</li>
            <li>sub sub sub item c</li>
            </ul></li>


        <li>sub sub item b</li>
        <li>sub sub item c</li>
    </ul>
</li>

<li><a href="#">Sub item b</a>
        <ul class="sub-menu">
        <li>sub sub item e</li>
        <li>sub sub item f</li>
        <li>sub sub item g</li>
</ul>
</li>
</ul>

JavaScript

function initMenu() {
    $(".sub-menu").hide();
    $(".current_page_item .sub-menu").show();
    $('#menu li a').click(

    function() {
        var checkElement = $(this).next();
        if ((checkElement.is('ul')) && (checkElement.is(':visible'))) {
            return false;
        }
        if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
            console.log(checkElement.parentsUntil('#menu'));
            $('#menu ul:visible').not(checkElement.parentsUntil('#menu')).slideUp('normal');
            checkElement.slideDown('normal');
            return false;
        }
    });
}
$(function() {
    initMenu();
});