The rewritten title is: How to implement automatic closing of submenu in jQuery
P粉312631645
P粉312631645 2023-09-16 09:10:19
0
2
941

I'm trying to create a jQuery dropdown menu for a mobile view. I'm new to jQuery and I'm using Toggle to hide and show submenus. My problem is that when I click on a menu item, the other submenus don't close automatically. For example, if I click menutwo, I want menuone to close automatically. How can I do this? please help.

jQuery(document).ready(function($) {
  $(".menuone").click(function() {
    $(".submenuone").toggle(200);
  });
  $(".menutwo").click(function() {
    $(".submenutwo").toggle(200);
  });
  $(".menuthree").click(function() {
    $(".submenuthree").toggle(200);
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="menu-menu" class="menu dropdown-menu">
  <li class="menuone"><a href="#">关于我们</a>
    <ul class="submenuone">
      <li>公司概况</a>
      </li>
    </ul>
  </li>
  <li class="menutwo"><a href="#">解决方案</a>
    <ul class="submenutwo">
      <li>应收账款融资和催收</li>
      <li>工人补偿融资></li>
    </ul>
  </li>
  <li class="menuthree"><a href="#">提供者类型</a>
    <ul class="submenuthree">
      <li>医生</a>
      </li>
      <li>药房</a>
      </li>
    </ul>
  </li>
</ul>

P粉312631645
P粉312631645

reply all(2)
P粉207483087

Made it finally.

Here is my answer

jQuery(document).ready(function($) {
  $(".menuone").click(function() {
  $(".submenuone").toggle(200);
  $(".submenutwo, .submenuthree").hide(200); // Hide other submenus
  });

$(".menutwo").click(function() {
$(".submenutwo").toggle(200);
$(".submenuone, .submenuthree").hide(200); // Hide other submenus
});

$(".menuthree").click(function() {
$(".submenuthree").toggle(200);
$(".submenuone, .submenutwo").hide(200); // Hide other submenus
});
});
P粉146080556

I would use event delegation and find other ULs and close them.

jQuery(document).ready(function($) {
  $("#menu-menu").on("click", "> li", function () {
     $("#menu-menu > li").not(this).find("ul").hide(200);
     $(this).find("ul").toggle(200);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="menu-menu" class="menu dropdown-menu">
  <li class="menuone"><a href="#">关于我们</a>
    <ul class="submenuone">
      <li>公司概况</a>
      </li>
    </ul>
  </li>
  <li class="menutwo"><a href="#">解决方案</a>
    <ul class="submenutwo">
      <li>应收账款融资和催收</li>
      <li>工人赔偿融资></li>
    </ul>
  </li>
  <li class="menuthree"><a href="#">供应商类型</a>
    <ul class="submenuthree">
      <li>医生</a>
      </li>
      <li>药房</a>
      </li>
    </ul>
  </li>
</ul>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!