点击带有儿童的菜单 [英] Click menu with children

查看:149
本文介绍了点击带有儿童的菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找某种类型的jQuery点击菜单,如果点击的 li 元素将打开另一个 ul 有孩子 - 这样的东西。

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>

所以当我点击Item 1列表,如果我点击Item 1 child 3,它会打开另一个列表,依此类推。

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.

看到一些关于 .next 但我不太确定。

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

推荐答案

这应该可以做你需要的:

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)

查看这里的工作示例

这里是一个滑动效果的示例(在注释中暗示)

注意

使用 .children 函数意味着一旦父对象重新扩展,所有的子扩展将被保留 - 对我来说,这似乎是自然的行为。

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.

如果您希望关闭父级重置所有子扩展,也会在下一次扩展父扩展时关闭,那么您可以使用 .find 方法替换 .children

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

此代码将应用于页面上的所有A链接,如果您需要更具体地了解应用于哪个A链接,您应该更改选择器。一个仅包含UL元素中的A链接的示例可能如下所示:

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

这篇关于点击带有儿童的菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆