如何切换下一个ul类? [英] How to toggle next ul class?

查看:105
本文介绍了如何切换下一个ul类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打开/关闭嵌套的子菜单,我有三层或四层嵌套的ul,它们都已关闭,但第一个是关闭的.当我开始单击元素时,下一个ul应该打开并切换显示/隐藏.下面的js不能完全满足我的要求.

I am trying to open/close nested sub menus, I have three or four levels of nested uls which are all closed but the first one. When I start clicking on the elements, the next ul should open and toggle show/hide. The js below it's not fully accomplishing what I am looking for.

CSS

.closed {
   display: none;
}

.opened {
   display: block;
}

HTML

<ul>
  <li><button type="button">TOGGLE</button>
     <ul class="closed">
        <li>Two
           <ul class="closed">
              <li>Three
                <ul class="closed">
                   <li>Four</li>
                </ul>
              </li>
           </ul>
         </li>
     </ul>
   </li>
</ul>

尝试js:

$("button").on("click", function(){
   $(this).parent().next("ul").toggle(function()  {
      $(this).removeClass("closed").addClass("opened");
    }, function() {
      $(this).removeClass("opened").addClass("closed");
    });
});

推荐答案

您应该使用$(this).next("ul")而不是$(this).parent().next("ul"),因为ul是按钮的下一个直接元素.您可以使用toggleClass方法来切换类,如下所示.

You should use $(this).next("ul") instead of $(this).parent().next("ul"), because ul is the immediate next element of the button. And you can use toggleClass method for toggling class like following.

$("button").on("click", function(){
    $(this).next("ul").toggleClass("closed opened");
});

这篇关于如何切换下一个ul类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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