使用 Javascript 在点击时隐藏和显示 <ul> 和 <li>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13528381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hiding and showing <ul> and <li> on click using Javascript
提问by OneMoreError
I need to show a few categories on my web page and their sub-categories as well. So I have arranged them in the form of nested <ul> <li>tags. I want the effect that only when a user clicks on one of the categories, all the sub-categories should become visible. Initially no sub-categories are visible.
我需要在我的网页上显示一些类别及其子类别。所以我把它们以nested <ul> <li>标签的形式排列。我想要的效果是,只有当用户单击其中一个类别时,所有子类别才应该可见。最初没有子类别是可见的。
In the body part, I have done this
在身体部分,我已经这样做了
<ul>
<li class="dropdown">Data mining and data warehousing
<ul>
<li>Data mining techniques</li>
<li>Knowledge discovery</li>
</ul>
</li>
<li class="dropdown">Soft computing and artificial intelligence
<ul>
<li>Fuzzy systems</li>
<li>Neural networks</li>
</ul>
</li>
</ul>
In the css part, I have done
在css部分,我已经完成了
li.dropdown ul {
display : none;
}
And I have added the following Javascript script in the head section of the html page
我在 html 页面的 head 部分添加了以下 Javascript 脚本
<script type="text/javascript">
$('li.dropdown').click(function() {
$(this).children('ul').toggle();
});
</script>
Initially, the effect works fine and all the sub categories are hidden. However, I want, say when I click on Data mining and data warehousing, then the two sub-categories should also become visible, which are Data mining techniquesand Knowledge discovery.
最初,效果很好,所有子类别都隐藏了。但是,我想说,当我点击 时Data mining and data warehousing,两个子类别也应该变得可见,它们是Data mining techniques和Knowledge discovery。
Also, when I click on other category, the sub-categories of previously opened categories should collapse again. How can I do that ?
此外,当我单击其他类别时,以前打开的类别的子类别应该再次折叠。我怎样才能做到这一点 ?
回答by Andrei
So the idea is to hide everything but the clicked li, and then toggle subcategory visibility for the clicked one:
因此,我们的想法是隐藏除 clicked 之外的所有内容li,然后为 clicked 切换子类别可见性:
$('li.dropdown').click(function() {
$('li.dropdown').not(this).find('ul').hide();
$(this).find('ul').toggle();
});
Here is the jsFiddlewith example.
这是带有示例的jsFiddle。
回答by Amit Garg
$('li.dropdown').click(function() {
$('.dropdown ul').hide();
$(this).children('ul').show();
});
Try this http://jsfiddle.net/7NYhe/
回答by janhenkes
Try the following:
请尝试以下操作:
$('li.dropdown').click(function() {
$(this).find('ul').toggle();
});

