简单的JQuery嵌套列表遍历问题 [英] Simple JQuery nested list traversing question

查看:51
本文介绍了简单的JQuery嵌套列表遍历问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我敢肯定它很简单,但是我花了数小时试图使其无法正常工作.

I have a problem that I'm sure is very simple, yet I have spent hours trying to get it to work to no avail.

每当单击父列表项时,我都试图显示一个嵌套列表.

I am trying to display a nested list whenever a parent list item is clicked.

这是JQuery:

<script type="text/javascript">
 $(document).ready(function() {

  $("#menu ul ul" ).hide();


$("#menu ul li").click(function() {
$(this).next().toggle();
});
});
</script>

这是HTML:

<div id="menu">
<ul>
<li><a id="database" href="#">Database</a></li>

<ul>
<li><a href="#">view database</a></li>
<li><a href="#">edit database</a></li>
</ul>

<li><a id="production" href="#">Production</a></li>
<ul>
<li><a href="#">add order</a></li>
<li><a href="#">plan orders</a></li>
</ul>
</ul>
</div>

现在,当我单击首选项时,正确的嵌套列表切换,但是当我单击嵌套时,它们也会切换.这一定与我选择第一个嵌套列表的方式有关……

Now When I click the fisrt ul li's the correct nested list toggles, however when I click the nested li's they too toggle. It must be something to do with the way I am selecting the first nested list...

非常感谢您的帮助!

推荐答案

首先,让我们获得一些有效的标记,<ul>元素不能是另一个<ul>的直接子代,它们应该位于<li>内,就像这样:

First, let's get some valid markup, the <ul> elements can't be direct children of another <ul>, they should be inside a <li>, like this:

<div id="menu">
    <ul>
        <li><a id="database" href="#">Database</a>            
            <ul>
                <li><a href="#">view database</a></li>
                <li><a href="#">edit database</a></li>
            </ul>
        </li>

        <li><a id="production" href="#">Production</a>
            <ul>
                <li><a href="#">add order</a></li>
                <li><a href="#">plan orders</a></li>
            </ul>
        </li>
    </ul>
</div>

之后,您只需要阻止click事件冒泡到父级<li>,就像这样:

After that, you just need to stop the click event from bubbling up to the parent <li>, like this:

$("#menu ul li").click(function(e) {
  $(this).children("ul").toggle();
  e.stopPropagation();
});

您可以在此处进行测试.

这篇关于简单的JQuery嵌套列表遍历问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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