jQuery toggle menu hide/show (close other menus when new menu opens)

余生颓废 提交于 2019-12-03 21:28:01

You can do something like this:

$(function() {
  $("ul li a").click(function() { 
      $(this).parent().next().toggle("fast").siblings("[id]").hide("fast");
  });
});

You can test it out here, what this does it toggle the sibling <li> still, but then looks at its .siblings() that have an ID attribute and .hide() them if show.


If the markup isn't locked in, you could simplify it further like this:

<ul class="navigation">
    <li class="toggle">Us</li>
    <li class="content">about thedot</li>
    <li class="toggle">Portfolio</li>
    <li class="content"></li>
    <li class="toggle">Contact</li>
    <li class="content">contact deets</li>
    <li class="toggle">Twitter</li>
    <li class="content">some twitter shit</li>
    <li><a href="#">Blog</a></li>
</ul>

And script like this:

$(function() {
  $("li.content").hide();
  $("ul.navigation").delegate("li.toggle", "click", function() { 
      $(this).next().toggle("fast").siblings(".content").hide("fast");
  });
});

It's a matter of preference, but I find this approach a bit cleaner and more style-able, check out the result here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!