使容器保持打开状态,以便首次单击每个导航项

Keep container open for first click of each nav item

本文关键字:单击 导航 状态      更新时间:2023-09-26

我正在尝试弄清楚如何做到这一点 - 我需要通过单击同级列表项来保持一个容器打开,然后在第二次单击时将其关闭。问题是返回到另一个链接并在其上留下处理程序。

这个概念是:

<ul id="nav">
    <li><a href="#">Nav Item Two</a></li>
    <li><a href="#">Nav Item Three</a></li>
    <li><a href="#">Nav Item Four</a></li>
 </ul>
<div id="nav-content">
    <!-- Content changed with Ajax -->
</div>

使用它,我将内容与 ajax 互换,因此单击将其返回到我的"导航内容"div 中。当我单击一个项目时,我希望内容div 打开,然后在单击下一个导航项链接时保持打开状态,但在第二次单击时关闭。

尝试使用取消绑定,但我认为这不合适,而且它不起作用。有什么想法吗?

您可以通过以下方式执行此操作:

  • 单击li时为其指定类
  • 从所有其他li中删除该类
  • 然后在隐藏或显示div 之前检查该类

本质上使用类来跟上上次单击li

$('#nav li').click(function(){
    
    // remove the `active` cass form all `li`s in `#nav` 
    // except the one that was clicked
    $('#nav li').not(this).each(function(){
          $(this).removeClass('active');
    });
    // check if clicked element has `active` class
    // if so it was just clicked for second time, close the div
    if( $(this).hasClass('active') ){
      $(this).removeClass('active');
      $('#nav-content').hide();
    }
    else{
      // if not it was clicked for the first time
      // show the div and make the clicked element `active`
      $(this).addClass('active');
      $('#nav-content').show();
    }
    
  
});
#nav-content{
  display:none;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="nav">
    <li><a href="#">Nav Item Two</a></li>
    <li><a href="#">Nav Item Three</a></li>
    <li><a href="#">Nav Item Four</a></li>
 </ul>
<div id="nav-content">
    <!-- Content changed with Ajax -->
  Here is some content
</div>