Click menu with children

2019-09-17 00:13发布

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.

3条回答
仙女界的扛把子
2楼-- · 2019-09-17 01:10

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/

查看更多
再贱就再见
3楼-- · 2019-09-17 01:15

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

查看更多
我命由我不由天
4楼-- · 2019-09-17 01:18

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(...
查看更多
登录 后发表回答