This question already has answers here:
avoid closing the menu if submenu items is clicked
                            
                                (3个答案)
                            
                    
                上个月关闭。
        

    

我试图通过子菜单制作菜单。如何排除子项目的点击事件?在我的代码段中,当我单击子项时。父级被删除.open类。



var menu = document.querySelectorAll('#menu > li')
if (menu.length) {
  for (var i = 0; i < menu.length; i++) {
    if (menu[i].classList.contains('has-sub')) {
      menu[i].addEventListener('click', function(event) {
          event.currentTarget.classList.toggle('open')
      })
    }
  }
}

.sub-menu { display: none }
.has-sub.open .sub-menu { display: block }

<ul id="menu">
  <li class="has-sub">
    <a href="#">Sub-memu</a>
    <ul class="sub-menu">
      <li><a href="#">Item</a></li>
    </ul>
  </li>
</ul>

最佳答案

您只需要从子菜单中调用event.stopPropagation



var menu = document.querySelectorAll('#menu > li')
if (menu.length) {
  for (var i = 0; i < menu.length; i++) {
    if (menu[i].classList.contains('has-sub')) {
      menu[i].addEventListener('click', function(event) {
          event.currentTarget.classList.toggle('open')
      })
    }
  }
}
// this is the important part
var submenus = document.querySelectorAll(".sub-menu");
for (var i = 0; i < submenus.length; i ++) {
  submenus[i].addEventListener("click", function (event) {
    event.stopPropagation();
  });
}

.sub-menu { display: none }
.has-sub.open .sub-menu { display: block }

<ul id="menu">
  <li class="has-sub">
    <a href="#">Sub-memu</a>
    <ul class="sub-menu">
      <li><a href="#">Item</a></li>
    </ul>
  </li>
</ul>

08-06 07:59