Javascript 通过 jQuery 显示/隐藏 <li>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6011259/
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
Show/hide <li> by jQuery
提问by James
I have html like
我有 html 喜欢
<ul>
<li class="dropdown">text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li class="dropdown">text</li>
<li>text</li>
<li>text</li>
<li class="dropdown">text</li>
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
CSS:
CSS:
li {display:none;}
li.dropdown {display:block;}
When we click on li.dropdown
, all the <li>
without classes, from the current to the next li.dropdown
, should become visible. And opposite action when we click it again - hide <li>
without class dropdown
.
当我们点击 时li.dropdown
,所有<li>
没有的类,从当前到下一个li.dropdown
,都应该变得可见。当我们再次点击它时,相反的动作 - 隐藏<li>
而不上课dropdown
。
How do I do this?
我该怎么做呢?
回答by lonesomeday
The correct way to do this would be with submenus, so:
正确的方法是使用子菜单,因此:
<ul>
<li class="dropdown">text
<ul>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
</li>
etc...
</ul>
You can then do
然后你可以做
$('li.dropdown').click(function() {
$(this).find('ul').slideToggle('slow');
});
Otherwise, you'll have to use nextUntil
:
否则,您将不得不使用nextUntil
:
$('li.dropdown').click(function() {
$(this).nextUntil('li.dropdown').slideToggle('slow');
});
This will have the disadvantage of hiding each of the nested li
elements individually, rather than as a block. Do the first if you can.
这将具有li
单独隐藏每个嵌套元素而不是作为块隐藏的缺点。如果可以,请先做。
回答by Daff
I would recommend using a nested list structure lik this:
我建议使用这样的嵌套列表结构:
<ul>
<li class="dropdown">text
<ul>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
</li>
<li class="dropdown">text
<ul>
<li>text</li>
<li>text</li>
</ul>
</li>
</ul>
Creat a CSS like this:
像这样创建一个 CSS:
li.dropdown ul {
display : none;
}
And then only show/hide the nested unordered lists:
然后只显示/隐藏嵌套的无序列表:
$('li.dropdown').click(function() {
$(this).children('ul').toggle();
});
回答by c-smile
If you have the item in $dropdown variable then you can use this:
如果您在 $dropdown 变量中有项目,那么您可以使用:
$dropdown.next( "li:not(.dropdown)" ).hide();
That will hide all not .dropdowns;
这将隐藏所有非 .dropdowns;
To do this until the next .dropdown you will need to use:
要在下一个 .dropdown 之前执行此操作,您需要使用:
$dropdown.next("li").each(...);