jQuery .toggle() to show and hide a sub sub-menu

2019-05-07 02:24发布

问题:

I'm using this question's code to make a show/hide toggle

jQuery .toggle() to show and hide a sub-menu

$('#menu-lateral .sub-menu').hide(); //Hide children by default

$('#menu-lateral > li > a').click(function() {
    event.preventDefault();
    $(this).siblings('.sub-menu').slideToggle('slow');
});

The problem is that my sub-menu has its own sub-menu with many items. Is there a way to adapt this code to work ALSO in the next level?

Important info: wordpress makes by default the child UL with the same class, so both are .sub-menu.

Like:

<ul id="menu-lateral" class="menu">
    <li id="menu-item-29"><a href="#">Parent Level 1</a>
        <ul class="sub-menu">
            <li id="menu-item-108"><a href="#">Parent Level 2</a>
                <ul class="sub-menu">
                    <li id="menu-item-104"><a href="#">Element</a></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

Fiddle: http://jsfiddle.net/qfygM/1/

Thanks for the help!

UPDATE: The solution may be found here >> http://jsfiddle.net/qfygM/7/

Made by Zenith.

$('#menu-lateral .sub-menu').hide(); //Hide children by default

$('#menu-lateral li a').click(function(event){
if ($(this).next('ul.sub-menu').children().length !== 0) {     
    event.preventDefault();
}
$(this).siblings('.sub-menu').slideToggle('slow');});

回答1:

Yes, in this case you could just use the descendant selector - $('#menu-lateral li a') as your selector as opposed to the direct child selector you're currently using - $('#menu-lateral > li > a').

jsFiddle here.

As you're now using the descendant selector, all future descending 'levels' will be targeted individually in your $(this).siblings('.sub-menu').slideToggle('slow'); statement, making it very easily extendable.