当孩子李被按下时如何停止对父母的切换类?

时间:2018-11-11 15:41:38

标签: jquery javascript-events nested next siblings

这是我的HTML:

<ul id="menu-mobile" class="menu menu-sliding">
  <li>
    <a href="javascript:void(0);">Home</a></span>
  </li>
  <li class="has-children">
    <a href="javascript:void(0);">IT Solutions</a>
    <span class="menu-item-toggle"><span></span></span>
    <ul class="sub-menu">
      <li class="has-children">
        <a href="javascript:void(0);">IT Services</a>
        <span class="menu-item-toggle"><span></span></span>
        <ul class="sub-menu">
          <li><a href="javascript:void(0);">Managed IT</a></li>
          <li><a href="javascript:void(0);">IT Support</a></li>
          <li><a href="javascript:void(0);">IT Consultancy</a></li>
          <li><a href="javascript:void(0);">Cloud Computing</a></li>
          <li><a href="javascript:void(0);">Cyber Security</a></li>
          <li><a href="javascript:void(0);">Custom Software</a></li>
        </ul>
      </li>
      <li class="has-children">
        <a href="">Industries</a>
        <span class="menu-item-toggle"><span></span></span>
        <ul class="sub-menu">
          <li><a href="javascript:void(0);">Banking</a></li>
          <li><a href="javascript:void(0);">Capital Markets</a></li>
          <li><a href="javascript:void(0);">Enterprise Technology</a></li>
          <li><a href="javascript:void(0);">Manufacturing</a></li>
          <li><a href="javascript:void(0);">Healthcare</a></li>
          <li><a href="javascript:void(0);">Higher Education</a></li>
          <li><a href="javascript:void(0);">Logistics</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

这是我的脚本:

$('ul.menu li.has-children').on('click', function () {
  $(this).toggleClass('menu-expand').siblings().removeClass('menu-expand');
});

外观如下:

enter image description here

现在的问题是,每当我单击嵌套的li的{​​{1}} It Services / Industries类都从父级.menu-expand中删除时,整个块都放在{ {1}}状态。

该如何解决?

1 个答案:

答案 0 :(得分:0)

我想您可以更改密钥以正确使用它,并且仅在一级李的情况下才使用它:

$('ul.menu li.has-children a').on('click', function () {
  $(this).parent().toggleClass('menu-expand').siblings().removeClass('menu-expand');
});

要正确解决此问题,将点击事件转移到A标签,并相应地转移到代码块的内部。

希望这会有所帮助。