slideToggle菜单和子菜单

时间:2018-10-26 11:51:24

标签: javascript jquery

我对slideToggle()有疑问。当我单击子菜单项时,我的ul和sub ul关闭。我有ul:

$('.menu-pages li').click(function() {
  $(this).children('.sub-menu').slideToggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="menu-pages">
  <li class="">
    <a href="#" target="_self" style="">
      <span>Информация</span>
    </a>
    <ul class="sub-menu" style="display: none;">
      <li class="">
        <a href="http://dev.giant.md/page/o-kompanii" target="_self" style="">
          <span>О нас</span>
        </a>
      </li>
      <li class="">
        <a href="#" target="_self" style="">
          <span>Бренды</span>
        </a>
        <ul class="sub-menu" style="">
          <li class="">
            <a href="http://dev.giant.md/page/giant" target="_self" style="">
              <span>Giant</span>
            </a>
          </li>
          <li class="">
            <a href="http://dev.giant.md/page/liv" target="_self" style="">
              <span>Liv</span>
            </a>
          </li>
          <li class="">
            <a href="http://dev.giant.md/page/shimano" target="_self" style="">
              <span>SHIMANO</span>
            </a>
          </li>
        </ul>
      </li>
    </ul>

当我单击父级li时,我会执行slideToggle()。但是我对孩子slideToggleul > li。当我单击孩子时,我关闭了父母ul。我该如何正确slideToggle()对父母和孩子分别进行开/关效果?

1 个答案:

答案 0 :(得分:0)

之所以发生这种情况,是因为顶级<li>包含整个子列表,并且菜单项上的click事件通过DOM向上传播,从而触发了其父级的click事件,包括顶级<li>

要阻止这种情况发生,只需在事件对象上使用stopPropgation方法:

$('.menu-pages li').click(function(event) {
  event.stopPropagation();
  $(this).children('.sub-menu').slideToggle();   
});