开发者

Simple JQuery nested list traversing question

开发者 https://www.devze.com 2023-01-28 21:46 出处:网络
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 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.

This is the JQuery:

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

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


$("#menu ul li").click(function() {
$(th开发者_如何学编程is).next().toggle();
});
});
</script>

and this is the 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...

Any help is much appreciated!


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>

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();
});

You can test it out here.

0

精彩评论

暂无评论...
验证码 换一张
取 消