代码之家  ›  专栏  ›  技术社区  ›  DeltaG

引导下拉菜单关闭上游子菜单

  •  2
  • DeltaG  · 技术社区  · 7 年前

    我有一个两级下拉列表,效果很好,但是当我添加另一级时,JS似乎正在删除 open 从上一个子菜单初始化,这意味着无法看到所需的第三级菜单,即使它确实获得了 打开 类已添加。

    我找到了这个JS:

      $(function() {
    
      $('li.dropdown-submenu').on('click', function(event) {
          event.stopPropagation();
          if ($(this).hasClass('open')){
              $(this).removeClass('open');
          } else {
              $('li.dropdown-submenu').removeClass('open');
              $(this).addClass('open');
         }
      });
    });
    

    我认为,这是在做上一个子菜单的意外关闭。HTML与 this 例子。

    使用该示例中JS的改编,我得到了第三个级别,但是当单击另一个子菜单时,任何给定的打开子菜单都不会自动关闭。

    $(document).ready(function(){
      $('.dropdown-submenu a').on("click", function(e){
        $(this).next('ul').toggle();
        e.stopPropagation();
        e.preventDefault();
      });
    });
    

    两者都需要最好的!

    3 回复  |  直到 7 年前
        1
  •  3
  •   inki    7 年前

    我想你差不多有了,你只需要寻找不同的点击。

    我在下面采取的方法是处理所有 a 单击,然后检查它是否有 test 如果没有 测试 然后它会隐藏所有子菜单并转到其默认的ref。

    <script>
    $(document).ready(function(){
      $('.dropdown-submenu a').on("click", function(e){
        if ($(this).hasClass('test')) {
          $(this).next('ul').toggle();
          e.stopPropagation();
          e.preventDefault();
        } else {
          $('.dropdown-submenu ul').hide();
        }
      });
    });
    </script>
    

    您更新的工作示例: https://www.w3schools.com/code/tryit.asp?filename=FUB7ECWP20DA

        2
  •  2
  •   synz    7 年前

    也许这就是你要找的。

    此代码用于在单击其他子菜单时关闭子菜单。

    Javascript

    $(document).ready(function(){
        $('.dropdown-submenu a.test').on("click", function(e){
    
        /* This is to hide all dropdown-menu children if the parent(dropdown-submenu) in the element have been clicked */ 
        $(this).next('ul').find('.dropdown-menu').each(function(){
            $(this).hide();
        });
    
        /* This is to find another dropdown-menu have has been opened and hide its submenu */   
        var xw = $(this);
        $(this).closest(".dropdown-menu").find('.dropdown-submenu a.test').not(xw).each(function(){
            if($(this).next("ul").is(":visible")){
                $(this).next("ul").hide();
            }
        });
    
        $(this).next('ul').toggle();
        e.stopPropagation();
        e.preventDefault();
        });
    });
    

    和JSFiddle示例: https://jsfiddle.net/synz/vasho634/

        3
  •  0
  •   Gaurav    7 年前

    我希望这是你想要的。这是解决办法,不是充分的证据,而是你想要的程度

    $(document).ready(function(){
      $('.dropdown-submenu a.test').on("click", function(e){
    
        siblingUl = $(this).parent().siblings("li.dropdown-submenu").children("ul").css("display");
        if(siblingUl == "block"){
        $(this).parent().siblings("li.dropdown-submenu").children("ul").toggle();
        }
        $(this).next('ul').toggle();
        e.stopPropagation();
        e.preventDefault();
      });
    });