简体   繁体   中英

How can i fix this jquery script for submenu?

This is the code and this is the result: you can see test the menu by clicking inside.

$(document).ready(function () {
    var $links = $('#menu-menu-1 .menu-item a').click(function () {



        var submenu = $(this).next();
        $subs.not(submenu).hide()
        submenu.toggle(500);
        $("#menu-2").slideToggle(300);
    });
    var $subs = $links.next(); });

The problem is that if I click on the menu it appears the submenu, but if I don't close the submenu that I have open and I open another voice in the menu it doesn't work properly.

If I click another .menu-item a when #menu-2 is open what happens? The script close and open another submenu correctly but my #menu-2 close only close. And then if I close .menu-item a so... #menu-2 open. How can I do to fix?

Try

$(document).ready(function () {
    var $menu2 = $("#menu-2");
    var $links = $('#menu-menu-1 .menu-item a').click(function () {
        var submenu = $(this).next();
        $subs.not(submenu).hide();
        var isVisible = submenu.stop(true, true).is(':visible');
        $menu2.stop(true, true);
        if (isVisible) {
            submenu.hide(500);
            $menu2.slideUp(300);
        } else {
            $menu2.slideUp(300, function () {
                $menu2.slideDown(300);
                submenu.show(500);
            });
        }
    });
    var $subs = $links.next();
});

I think you could simplify what you're trying to do with something along these lines (untested):

$(function () { 
    var menuItems = $('#menu-menu-1 > li');
    var submenus = $('ul', menuItems)

    menuItems.click(function () {

        submenus.slideUp(); // Hide all menus to their default hidden state
        var submenu = $('ul', $(this)); // Show the child menu for the clicked menu
        submenu.toggle(500);
    });
});

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