[英]Hiding and showing <ul> and <li> on click using Javascript
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. 因此,我以nested <ul> <li>
标记的形式排列了它们。 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. 最初,没有子类别可见。
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页面的开头部分添加了以下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 techniques
and 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 ? 我怎样才能做到这一点 ?
So the idea is to hide everything but the clicked li
, and then toggle subcategory visibility for the clicked one: 因此,其想法是隐藏除单击的li
所有内容,然后为单击的li
切换子类别的可见性:
$('li.dropdown').click(function() {
$('li.dropdown').not(this).find('ul').hide();
$(this).find('ul').toggle();
});
Try the following: 请尝试以下操作:
$('li.dropdown').click(function() {
$(this).find('ul').toggle();
});
$('li.dropdown').click(function() {
$('.dropdown ul').hide();
$(this).children('ul').show();
});
Try this http://jsfiddle.net/7NYhe/ 试试这个http://jsfiddle.net/7NYhe/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.