我正在尝试弄清楚如何做到这一点——我需要通过单击同级列表项使一个容器保持打开状态,然后在第二次单击时将其关闭。问题是返回到另一个链接并在其上留下一个处理程序。
这个概念是:
<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 交换内容,因此单击会将其返回到我的“nav-content”div。当我单击一个元素时,我希望内容 div 打开,然后在单击下一个导航元素链接时保持打开状态,但在第二次单击时关闭。
尝试使用 unbind,但我认为这不合适,而且没有用。有什么想法吗?
最佳答案
您可以通过以下方式做到这一点:
- 当你点击它时给
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>
关于javascript - 第一次点击每个导航项时保持容器打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27891332/