如何防止同一项目上的多个 slidetoggles

How to prevent multiple slidetoggles on the same item

我目前有一个带有子 UL 的列表。单击列表项时,我希望 UL 滑动切换。这我已经实现了。我目前遇到的问题是,如果我单击已打开的同一项目以将其关闭,它会执行双重切换。值得一提的是,我希望一次只打开一个子 ul。

HTML

<div class="top">
 <ul>
  <li><a href="#"> Item </a></li>
<li class="drop"><a href="#"> Item Drop </a>
  <ul class="sub">
    <li><a href="#"> Sub Item </a></li>
    <li><a href="#"> Sub Item </a></li>
    <li><a href="#"> Sub Item </a></li>
  </ul>
</li>
<li><a href="#"> Item </a></li>
<li><a href="#"> Item </a></li>
<li class="drop"><a href="#"> Item Drop</a>
  <ul class="sub">>
    <li><a href="#"> Sub Item </a></li>
    <li><a href="#"> Sub Item </a></li>
    <li><a href="#"> Sub Item </a></li>
  </ul>
</li>
</ul>
</div>

CSS

ul {
  li {
    ul {
      display:none;
    }
  }
}

JS

$('.drop').click(function(){
  $('.sub').slideUp();
  $(this).children('.sub').slideToggle();
});

http://codepen.io/anon/pen/RRZPvZ

尝试以下方法

$('.drop').click(function(e){
  if($(e.target).closest('ul').is(':not(.sub)')) {//if the clicked element is has a ul that is not .sub we slide them up
  $('.sub').slideUp();}
  $(this).children('.sub').slideToggle();
});

或:

$('.drop').click(function(e){
  $('.sub').not( $(this).children('.sub')).slideUp();//hide all except the one we want to display
  $(this).children('.sub').slideToggle();
});