简体   繁体   中英

making a vertical sliding menu with jquery

here's my html:

<ul id="dmenu">
    <li><a href="#">menu item one</a></li>

    <li><a href="#">menu item two</a>
            <ul class="displayNone">
                <li><a href="#">menu item one</a>
            </ul>
    </li>
</ul>

When the user clicks on one of the a tags, I want my code to check wether there are any ul tags in the parent li tag. If there are, I then want to preventdefault action for the a tag and slideToggle the child ul element

my jquery atm:

$('#dmenu > a').click(function(e) {
    if (this.parent().has('ul')) {
        e.preventDefault();
        $(this).children().slideToggle();
    }
});

you are doing the slide toggle on the child of the a

change $(this).children().slideToggle(); to

$(this).parent().children('ul').slideToggle();

also your selector #dmenu > a is wrong - your top level menu doesn't have that id and if it did there are no direct anchors as children of the ul - remove the > and add the id dmenu to you top ul or container element

Edit

As pointed out by Austin, as you have nested lists you may want to limit your click events to the top level only so you can use the #dmenu > li a

Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM