Click menu with children

2019-09-17 01:10发布

问题:

I am looking for some sort of jQuery click menu that will open up another ul if the clicked li element has children - something like this.

<ul>
    <li><a href"#">Item 1</a>
        <ul>
            <li><a href"page1.html">Item 1 child 1</a></li>
            <li><a href"page2.html">Item 1 child 2</a></li>
            <li>
                <a href"#">Item 1 child 3</a>
                <ul>
                    <li><a href"#">Item 1 child 3 child</a></li>
                </ul>
            </li>
        </ul>
    </li>
    <li><a href"page3.html">Item 2</a></li>
    <li><a href"page4.html">Item 3</a></li>
</ul>

So when I click "Item 1" it will open up the new list and if I click "Item 1 child 3" it will open yet another list and so forth and so on.

I think I once saw some about .next but I am not quite sure.

回答1:

This should do what you need:

$("a").click(function(e){
   $(this).closest("li").children("ul").toggle();
});​

$("a").click();//quick hack to hide all children to start with (if desired)

See here for a working example

Here is an example with a sliding effect (as hinted in comments)


NOTES

Using the .children function will mean that all "sub-expansions" will be "retained" once the parent is re-expanded - to me this seems like the natural behaviour.

If you would prefer that closing a parent reset all sub expansions to also be closed the next time the parent is expanded, then you can use the .find method in replace of .children

Also, it should be considered that this code will apply to all A links on the page, if you need to be more specific about which A links this applied to you should change the selector. One example to only include A links within a UL element might look like this:

$("ul a").click(...


回答2:

Using jQuery accordion plugin would be an ideal approach to your requirement. More details of how to implement it, can be found here jQuery Accordion



回答3:

Not the full implementation, but this should help I guess :

$("list").click(function(){
  $(this).find("ul").show();
});

That is, you can use "find()" to get the children elements.

EDIT: If you want the fisrt occurrence then use the "first()" api.

Ref : http://api.jquery.com/first/