gpt4 book ai didi

javascript - 子级不触发父级函数

转载 作者:行者123 更新时间:2023-12-01 01:48:55 27 4
gpt4 key购买 nike

我有一个菜单,并为文档设置了一个偶数监听器,如果单击 a 标记,则会执行一个函数,但由于某种原因,当单击 anchor 标记内的元素时,不会触发该函数。也许我错了,但是单击子元素时执行父函数的默认冒泡行为不是吗?

document.addEventListener('click', function(e){
if(e.target.tagName=="A"){
alert('BUTTON CLICKED');
}
})
body {
padding:0;
margin:0;
background-color: #252526;
}
* {
box-sizing: content-box;
font-family: 'arial', 'Arial';
}
a {
text-decoration: none;
color:white;
}
header {
position: fixed;
z-index:10;
background-color:#2e2f30;
bottom: 0;
left:0;
right:0;
padding: 10px 0px;
display: block;
}
nav {
display: block;
}
ul.navbar, li.nav-item {
list-style-type: none;
padding:0;
margin:0;
}
.navbar {
width:100%;
position: relative;
display: flex;
}
.nav-item {
width:25%;
text-align: center;
color:white;
}
.nav-item p {
margin:0;
padding:0;
font-size: .9em;
font-weight: 100;
}
<link href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<nav>
<ul class="navbar">
<li class="nav-item">
<a href="#home">
<i class="fas fa-home"></i>
<p>Home</p>
</a>
</li>
</ul>
</nav>
</header>
<div class="page active-page" id="home">

</div>

请注意,如果您单击 anchor 标记但未单击其子元素,则该函数将执行。如何让 anchor 标签的子标签也执行该函数?任何帮助表示赞赏。

最佳答案

您可以在 OR 运算符中使用另一个条件,即 e.target.parentNode.tagName == "A" 来检查 anchor 元素是否是单击元素,它将为您工作:

document.addEventListener('click', function(e){
if(e.target.tagName=="A" || e.target.parentNode.tagName == "A"){
alert('BUTTON CLICKED');
}
})
body {
padding:0;
margin:0;
background-color: #252526;
}
* {
box-sizing: content-box;
font-family: 'arial', 'Arial';
}
a {
text-decoration: none;
color:white;
}
header {
position: fixed;
z-index:10;
background-color:#2e2f30;
bottom: 0;
left:0;
right:0;
padding: 10px 0px;
display: block;
}
nav {
display: block;
}
ul.navbar, li.nav-item {
list-style-type: none;
padding:0;
margin:0;
}
.navbar {
width:100%;
position: relative;
display: flex;
}
.nav-item {
width:25%;
text-align: center;
color:white;
}
.nav-item p {
margin:0;
padding:0;
font-size: .9em;
font-weight: 100;
}
<link href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<nav>
<ul class="navbar">
<li class="nav-item">
<a href="#home">
<i class="fas fa-home"></i>
<p>Home</p>
</a>
</li>
</ul>
</nav>
</header>
<div class="page active-page" id="home">

</div>

关于javascript - 子级不触发父级函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51746569/

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