简体   繁体   中英

Show/hide <li> by jQuery

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

How do I do this?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM