Hide/Toggle submenu when clicking on another menu item

╄→гoц情女王★ 提交于 2019-12-05 06:15:47

问题


This is what I have right now: JSfiddle

When you click on Category 1 and then on Category 2, I would like the sub menu of Category 1 to close. How can I achieve that?

All I have achieved right now, is to close the sub menu(s) when clicking anywhere on the screen except on the menu:

$(function () {
$('nav ul li').not("nav ul li ul li").click(function(e){
    $(this).children('ul').stop().toggle();
    e.stopPropagation();
});
$("nav ul li ul li").click(function(e){
    $(this).children('ul').stop().toggle();
    e.stopPropagation();
});
});
$(document).click(function() {
    $("nav ul li ul").hide();
});

Thanks a lot for any responses!


回答1:


Just hide all li's before toggling current li -

$('nav ul li').not("nav ul li ul li").click(function (e) {
    e.stopPropagation();
    $("nav ul li ul").hide();
    $(this).children('ul').stop().toggle();
});

Demo -----> http://jsfiddle.net/rd6bX/17/




回答2:


Incase you have multiple levels you could achieve this with just one click handler rather than defining separate handlers for each level:

$(function () {
    $('nav > ul > li a').click(function (e) {
         e.preventDefault();
        var $parentli = $(this).closest('li');
        $parentli.siblings('li').find('ul:visible').hide();
        $parentli.find('> ul').stop().toggle();
    });

});

Fiddle




回答3:


$('ul',$(this).siblings()).slideUp(); add this after toggling a ul, to look for ul in all sibling li elements and hide them.

Like this :

$(function () {
$('nav ul li').not("nav ul li ul li").click(function(e){
    $(this).children('ul').stop().toggle();
    $('ul',$(this).siblings()).slideUp();
    e.stopPropagation();
});
$("nav ul li ul li").click(function(e){
    $(this).children('ul').stop().toggle();
    e.stopPropagation();
});
});
$(document).click(function() {
    $("nav ul li ul").hide();
});


来源:https://stackoverflow.com/questions/17264609/hide-toggle-submenu-when-clicking-on-another-menu-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!