最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Showhide <li> by jQuery - Stack Overflow

programmeradmin4浏览0评论

I have html like

<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:

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 bee visible. And opposite action when we click it again - hide <li> without class dropdown.

How do I do this?

I have html like

<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:

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 bee visible. And opposite action when we click it again - hide <li> without class dropdown.

How do I do this?

Share Improve this question edited Jun 3, 2012 at 17:47 Gilles 'SO- stop being evil' 108k38 gold badges215 silver badges260 bronze badges asked May 15, 2011 at 21:08 JamesJames 43.6k54 gold badges137 silver badges163 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

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:

$('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.

I would remend 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:

li.dropdown ul {
    display : none;
}

And then only show/hide the nested unordered lists:

$('li.dropdown').click(function() {
    $(this).children('ul').toggle();
});

If you have the item in $dropdown variable then you can use this:

$dropdown.next( "li:not(.dropdown)" ).hide();

That will hide all not .dropdowns;

To do this until the next .dropdown you will need to use:

$dropdown.next("li").each(...);
$("li.dropdown").click(function() {
    $(this).nextUntil(".dropdown").toggle();
});

Fiddle

发布评论

评论列表(0)

  1. 暂无评论