简体   繁体   中英

jquery : ul, li parent multiple child sub-child toggling

my main question is as follows: how to show only the first subchild of a ul or li upon clicking the enclosing parent.

eg:

<ul> Grandparent
  <li> Child1 <li> Grandchild11</li></li>
  <li> Child2 <li>GrandChild21</li><li>grandchild22</li></li>
</ul>

so, for example I would like something to the effect of

$('ul').click(function(){
  $('ul').children('first li').toggle();
});
$('li').click(function(){
  $('li').children('first li').toggle();
});

meaning: when i click ul, i only see the first child node (child1 and child2 will be shown, but not the grandchildren). when i click child1 or child2 i see the respective grandchild. grandchild is not shown upon clicking grandparent, only upon clicking child1 or child2.

i know i am reinventing the wheel of some pre-coded solution, but any help would be largely appreciated!

You need 2 steps here, first fix the HTML to be valid (a <li> has to be in a <ul> or <ol> ), like this:

<ul> 
    <li>Grandparent
        <ul>
          <li> Child1 
              <ul><li> Grandchild11</li></ul>
          </li>
          <li> Child2 
              <ul><li>GrandChild21</li><li>grandchild22</li></ul>
          </li>
        </ul>
    </li>
</ul>​

Then your click handler looks like this:

$('li').click(function(e){
  $(this).children('ul').slideToggle();
  e.stopPropagation();
});​

You can view a demo here , they key here is .stopPropagation() on the event passed into the click handler. This prevents the click event from bubbling up, causing the parent to also toggle the children beneath them...comment out this line in the demo to see some very undesirable behavior :)

Oh, and as Mvan mentions in comments, use some CSS to hide the children initially like the demo does:

ul li ul { display: none; }​

Use the > selector .

Note that nesting li elements is not allowed. Use a div or something else inside the li .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM