jQuery UL LI折叠其下的所有展开子级

时间:2019-02-20 07:10:23

标签: javascript jquery

我的列表顺序如下:

<ul>
    <li>level 1 a
        <ul>
            <li>level 2 a
                <ul>
                    <li>level 3 a</li>
                    <li>level 3 b</li>
                </ul>
            </li>
            <li>level 2 b</li>
        </ul>
    </li>
    <li>level 1 b
        <ul>
            <li>level 2 c
                <ul>
                    <li>level 3 c</li>
                    <li>level 3 c</li>
                </ul>
            </li>
            <li>level 2 d</li>
            <li>level 2 e</li>
        </ul>
    </li>
</ul>

和jquery看起来像这样:

$(document).ready(function(){
  $('li').click(function(ev) {
    ev.stopPropagation();
      $(this).children('ul').show();
      $(this).prev().children('ul').hide();
      $(this).siblings().children('ul li ul').hide();
      $(this).next().children('ul').hide();
  }); 
  $('li > ul').hide();
});

当前情况:

1)我单击 1a级,然后单击 2a级,现在扩展了1a级和2a级

2)我单击 1b级,然后单击 1a级,我仍然看到1a级,并且其子级已展开。

>

我想要的结果是:

当我单击1a级别时,它将折叠所有内容,而不是显示我之前单击的所有内容,如果我单击该1st级别,则将显示1b级别。

jsfiddle

任何帮助都会很棒。谢谢

1 个答案:

答案 0 :(得分:1)

使用此方法单击children ul sibling时,您可以在li上调用hide

 $('li').click(function(ev) {
    $(this).siblings('li').click(function() {
      $(this).siblings('li').children('ul').hide()
    })

$(document).ready(function() {
  $('li').click(function(ev) {
    $(this).siblings('li').click(function() {
      $(this).siblings('li').children('ul').hide()
    })
    
      $(this).children('ul').children('li').children('ul').hide()
   
   
    ev.stopPropagation();
    $(this).parent('ul').show();
     $(this).children('li').hide();
    $(this).siblings('li').children('ul li ul').hide();
    $(this).children('ul').show();
    $(this).prev('li').children('ul li ul').hide();
    $(this).next().children('ul').hide();
  });
  $('li > ul').hide();
});
current situation: 1) i click on level 1 a then level 2 a,
now level 1 a and level 2 a are expanded 2) i click on level 1 b,
then i click back the level 1 a,
i still see the level 1 a and its child is expanded. the outcome i want is: when i click back level 1 a,
it will collapse everything,
instead of showing everything that i clicked before,
same goes to level 1 b,
if i click that 1st.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>level 1 a
    <ul>
      <li>level 2 a
        <ul>
          <li>level 3 a</li>
          <li>level 3 b</li>
        </ul>
      </li>
      <li>level 2 b</li>
    </ul>
  </li>
  <li>level 1 b
    <ul>
      <li>level 2 c
        <ul>
          <li>level 3 c</li>
          <li>level 3 c</li>
        </ul>
      </li>
      <li>level 2 d</li>
      <li>level 2 e</li>
    </ul>
  </li>
</ul>