gpt4 book ai didi

javascript - 点击事件目标排除子项

转载 作者:行者123 更新时间:2023-12-02 21:17:27 25 4
gpt4 key购买 nike

我尝试制作一个带有子菜单的菜单。如何排除子项目的点击事件?在我的代码片段中,当我单击子项目时。父级已删除 .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>

关于javascript - 点击事件目标排除子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60932207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com