4

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');});
4

2 回答 2

4

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.

于 2013-07-09T19:31:17.873 回答
0

One alternative would be to use $el.toggleClass(hideClass) ( or $el.addClass(hideClass) & $el.removeClass(hideClass) ) on the elements.

Then define the .hideClass {display: none} in your stylesheet.

I don't think this can be used in conjunction with toggle() though, so you'd have to stick with this method of hiding/displaying element.

于 2021-09-30T01:29:21.237 回答