简体   繁体   English

jQuery简单垂直手风琴菜单

[英]jQuery Simple Vertical Accordion Menu

how can i do when i click 'Item' it will open and when click again it will close in Vertical Accordion Menu: 当我单击“项目”时,该怎么办?当再次单击时,它将在“垂直手风琴菜单”中关闭:

<style>
    #nav { float: left; width: 280px; border-top: 1px solid #999; border-right: 1px solid #999; border-left: 1px solid #999; } #nav li a { display: block; padding: 10px 15px; background: #ccc; border-top: 1px solid #eee; border-bottom: 1px solid #999; text-decoration: none; color: #000; } #nav li a:hover, #nav li a.active { background: #999; color: #fff; } #nav li ul { display: none; // used to hide sub-menus } #nav li ul li a { padding: 10px 25px; background: #ececec; border-bottom: 1px dotted #ccc; }
    </style>  

    <ul id="nav">
      <li><a href="#">Item 1</a>
        <ul>
          <li><a href="#">Sub-Item 1 a</a></li>
          <li><a href="#">Sub-Item 1 b</a></li>
          <li><a href="#">Sub-Item 1 c</a></li>
        </ul>
      </li>
      <li><a href="#">Item 2</a>
        <ul>
          <li><a href="#">Sub-Item 2 a</a></li>
          <li><a href="#">Sub-Item 2 b</a></li>
        </ul>
      </li>
    </ul>


<script type="text/javascript">
$(document).ready(function () { 
  $('#nav > li > a').click(function(){
    if ($(this).attr('class') != 'active'){
      $('#nav li ul').slideUp();
      $(this).next().slideToggle();
      $('#nav li a').removeClass('active');
      $(this).addClass('active');
    }
  });
});
</script> 

when i click Item 1,Item 2 it will open sub menus but if i click it again it did not close it. 当我单击项目1,项目2时,它将打开子菜单,但是如果我再次单击它,则它没有关闭。

You need an else in your jquery to catch the click if the item is already active 如果项目已经active则需要在jquery中使用else来捕获点击

 $(document).ready(function () { $('#nav > li > a').click(function(){ if ($(this).attr('class') != 'active'){ $('#nav li ul').slideUp(); $(this).next().slideToggle(); $('#nav li a').removeClass('active'); $(this).addClass('active'); } else { $('#nav li ul').slideUp(); $('#nav li a').removeClass('active'); } }); }); 
 #nav li ul { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="nav"> <li><a href="#">Item 1</a> <ul> <li><a href="#">Sub-Item 1 a</a></li> <li><a href="#">Sub-Item 1 b</a></li> <li><a href="#">Sub-Item 1 c</a></li> </ul> </li> <li><a href="#">Item 2</a> <ul> <li><a href="#">Sub-Item 2 a</a></li> <li><a href="#">Sub-Item 2 b</a></li> </ul> </li> </ul> 

Didn't work because it didn't run any code on links that already had the active class. 没有用,因为它没有在已经具有active类的链接上运行任何代码。

You can achieve what you want with less code. 您可以用更少的代码来实现所需的功能。

$('#nav > li > a').click(function(){
    $('#nav > li > a').not(this).removeClass('active').next().slideUp();
    $(this).toggleClass('active').next().slideToggle();
});

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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