简体   繁体   中英

Jquery only allow one menu item to be expanded

So I have this code from a previous question: http://jsfiddle.net/928Dj/4/

$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function(e) {
      $(this).next('ul').toggle();
});

I was wondering if anyone could tell me how I allow it to still be toggled open and closed, but also make it so if one menu is open and I click to open another menu, it closes the first one, meaning only one menu can be open at any time.

Try to hide the opened ul elements first and then toggle the current element,

 $("ul.opt").addClass("hidden");
  $('#filter > li > a').on("click", function (e) {
    var cache = $(this).next('ul');
    $('#filter ul:visible').not(cache).hide();
    cache.toggle();
  });

DEMO

You can hide all the visible submenus before showing the current one as follows

$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function(e) {
  var ul = $(this).next('ul');
  $('ul li ul:visible').not(ul).hide();
  ul.toggle();
});

Demo

This is the best way. You can also try this:

$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function(e) {
      $(this).next('ul').toggle();
      $(this).parent().siblings().find('.opt').hide();
});

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM