Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 单击下拉菜单中包含子菜单的列表项,关闭其余项,但不';不要扩展新的_Javascript_Jquery_Drop Down Menu_Toggle_Submenu - Fatal编程技术网

Javascript 单击下拉菜单中包含子菜单的列表项,关闭其余项,但不';不要扩展新的

Javascript 单击下拉菜单中包含子菜单的列表项,关闭其余项,但不';不要扩展新的,javascript,jquery,drop-down-menu,toggle,submenu,Javascript,Jquery,Drop Down Menu,Toggle,Submenu,我正在创建一个下拉切换菜单,但我有一个问题,我不能把我的头围绕它。单击列表项可扩展其子项,但是,当列表展开时,当单击另一个列表时,第一个列表会收缩,但第二个列表在再次单击之前不会展开。我如何解决这个问题 单击列表时,一个类被切换将添加到其顶部父容器中,以便我可以使用jQuery创建条件-以下是代码: $('#main-navigation a').click(function (e) { /* Finding the drop down list that corresponds to the

我正在创建一个下拉切换菜单,但我有一个问题,我不能把我的头围绕它。单击列表项可扩展其子项,但是,当列表展开时,当单击另一个列表时,第一个列表会收缩,但第二个列表在再次单击之前不会展开。我如何解决这个问题

单击列表时,一个类
被切换
将添加到其顶部父容器中,以便我可以使用jQuery创建条件-以下是代码:

$('#main-navigation a').click(function (e) {

/* Finding the drop down list that corresponds to the current section: */
var $dropdownMenu = $(this).next();

if ($dropdownMenu.hasClass('sub-menu')) { /* Checking if drop down menu exists for this menu item */
    if ($('.nav-menu > li').hasClass('toggled')) { /* There is toggled menu */
        if (($(this).parents().hasClass('toggled')) && (!$(this).parent().hasClass('toggled'))) {
            // The curent element has only a not-direct parent with "toggled" e.g. the element is deep link!');
            $dropdownMenu.slideToggle('fast');
        } else {
            //If the element is a top link, the class is removed and the lists dissappear
            $('li.toggled').removeClass('toggled').children('ul').slideUp('fast');
        }

    } else {
        // If there isn't a toggled menu, the current menu expands and a class is added
        $dropdownMenu.slideToggle('fast').parent('.nav-menu > li').addClass('toggled');
    }

}
})
整个HTML、CSS和JS代码如下:


我甚至不确定这是否是制作这样一个菜单的最佳方式。

在这里做了一些更改:

将代码简化为:

$('#main-navigation a').click(function (e) {
   /* Finding the drop down list that corresponds to the current section: */
   var dropdownMenu = $(this).next();

   if ($(this).parent('li').children('.sub-menu').length > 0) {
      $('.sub-menu').not(dropdownMenu).not(dropdownMenu.parents()).slideUp('fast');
      $(dropdownMenu).slideToggle('fast');
   }
});

我在开始时也尝试过这段代码,但问题是它没有扩展项目类别2中的子菜单:(哦,太好了,解决了它!=]我只有一个问题,它是否可以这样创建,即单击三个链接中的最后一个链接不会滑动菜单?@jam6549谢谢!你太棒了,如果可以的话,我会再次投票。@jam6549