[英]how to have a <li> list hidden until the <ul> containing it is clicked
I have subgroups of li rows, contained in some ul lists. 我有li行的子组,包含在一些ul列表中。 When the page opens all of the rows are displayed. 当页面打开时,将显示所有行。 I'd like it to have the li's hidden until the ul containing them is clicked. 我希望隐藏li,直到单击包含它们的ul。
I know you can use css "display:none" to have them hidden on page open, but being a beginner with javascript I'm not sure how to get the list to expand when its clicked. 我知道您可以使用css“ display:none”将其隐藏在打开的页面上,但是作为javascript的初学者,我不确定如何在单击列表时扩展列表。
Thanks 谢谢
I'd use toggle along with the gt
selector to hide elements beyond a certain number. 我会与gt
选择器一起使用toggle来隐藏超出一定数量的元素。
lis = $("li:gt(0)").hide(); $("ul").click(function () { lis.toggle(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Expand</li> <li>A</li> <li>B</li> <li>C</li> <li>D</li> </ul>
You can try it like, 您可以尝试一下,
$('ul.subgroups').on('click',function(){ // will work only if you have at least a single li which is visible
if ($(this).children('li:hidden').length) {
$(this).children('li:hidden').show();
}
});
Snippet, 片段中,
$(function() { $('ul.subgroups').on('click', function() { if ($(this).children('li:hidden').length) { $(this).children('li:hidden').show(); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Item 1</li> <li>Item 2 <ul class="subgroups"> <li> Sub Item 2-1</li> <li style="display:none"> Sub Item 2-2</li> </ul> </li> <li>Item 3 <ul class="subgroups"> <li> Sub Item 3-1</li> <li style="display:none"> Sub Item 3-2</li> </ul> </li> </ul>
You can use jQuery toggle
for this 您可以为此使用jQuery toggle
$('li a').click(function(){ $(this).siblings('ul').toggle(); })
ul { padding: 0px; list-style: none; } li { display: block } li ul { display: none; padding-left: 10px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li><a href="#" title="">first</a> <ul> <li><a href="#" title="">first</a></li> <li><a href="#" title="">second</a></li> <li><a href="#" title="">third</a></li> <li><a href="#" title="">fourth</a></li> <li><a href="#" title="">fifth</a></li> </ul> </li> <li><a href="#" title="">second</a></li> <li><a href="#" title="">third</a> <ul> <li><a href="#" title="">first</a></li> <li><a href="#" title="">second</a></li> <li><a href="#" title="">third</a></li> <li><a href="#" title="">fourth</a></li> <li><a href="#" title="">fifth</a></li> </ul> </li> <li><a href="#" title="">fourth</a></li> <li><a href="#" title="">fifth</a></li> </ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.