2017-05-31 225 views
0

如何在丢失焦点时更新此代码以隐藏菜单项。 做出选择并再次点击教程按钮后,所有菜单项仍然打开。多级下拉菜单项

请尝试。

工作例如: https://www.w3schools.com/Bootstrap/tryit.asp?filename=trybs_ref_js_dropdown_multilevel_css&stacked=h

enter image description here

<!DOCTYPE html> 
 
    <html> 
 
    <head> 
 
     <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
 
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 
    <style> 
 
    .dropdown-submenu { 
 
     position: relative; 
 
    } 
 
    
 
    .dropdown-submenu .dropdown-menu { 
 
     top: 0; 
 
     left: 100%; 
 
     margin-top: -1px; 
 
    } 
 
    </style> 
 
    </head> 
 
    <body> 
 
     
 
    <div class="container"> 
 
     <h2>Multi-Level Dropdowns</h2> 
 
     <p>In this example, we have created a .dropdown-submenu class for multi-level dropdowns (see style section above).</p> 
 
     <p>Note that we have added jQuery to open the multi-level dropdown on click (see script section below).</p>           
 
     <div class="dropdown"> 
 
     <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Tutorials 
 
     <span class="caret"></span></button> 
 
     <ul class="dropdown-menu"> 
 
      <li><a tabindex="-1" href="#">HTML</a></li> 
 
      <li><a tabindex="-1" href="#">CSS</a></li> 
 
      <li class="dropdown-submenu"> 
 
      <a class="test" tabindex="-1" href="#">New dropdown <span class="caret"></span></a> 
 
      <ul class="dropdown-menu"> 
 
       <li><a tabindex="-1" href="#">2nd level dropdown</a></li> 
 
       <li><a tabindex="-1" href="#">2nd level dropdown</a></li> 
 
       <li class="dropdown-submenu"> 
 
       <a class="test" href="#">Another dropdown <span class="caret"></span></a> 
 
       <ul class="dropdown-menu"> 
 
        <li><a href="#">3rd level dropdown</a></li> 
 
        <li><a href="#">3rd level dropdown</a></li> 
 
       </ul> 
 
       </li> 
 
      </ul> 
 
      </li> 
 
     </ul> 
 
     </div> 
 
    </div> 
 
    
 
    
 
    <script> 
 
    $(document).ready(function(){ 
 
     $('.dropdown-submenu a.test').on("click", function(e){ 
 
     $(this).next('ul').toggle(); 
 
     e.stopPropagation(); 
 
     e.preventDefault(); 
 
     }); 
 
    }); 
 
    </script> 
 
    
 
    </body> 
 
    </html>

回答

0

你可能分裂与显示2个不同的功能切换和隐藏UL的。然后你可以在隐藏函数中添加隐藏所有孩子ul的代码。

像这样的东西可以帮助你或许:

$(document).ready(function(){ 
    $('.dropdown-submenu a.test').on("click", function(e){ 

    if ($(this).next('ul').is(":visible")) { 
     $(this).children().hide(); 
    } else { 
     $(this).next('ul').show(); 
    } 

    e.stopPropagation(); 
    e.preventDefault(); 
    }); 
}); 

注:我没有测试此还,所以我的代码可能有错,我只想告诉你我在想什么的。