【发布时间】:2022-06-18 22:53:46
【问题描述】:
我有一个包含多个子元素的父元素,其中一些有自己的侦听器,而另一些则没有。父元素具有单击处理程序,我只想在单击父元素本身而不是任何子元素时运行它。
document.getElementById('parent').addEventListener('click', ()=> console.log('parent clicked'))
document.getElementById('child2').addEventListener('click', ()=> console.log('child2 clicked'))
#parent {
height: 300px;
width: 300px;
background-color: Lightgreen;
wrap: true;
display: flex;
flex-direction:column;
gap: 20px;
padding: 50px 50px;
}
#parent * {
height: 100px;
width: 100px;
background-color: white;
text-align: center;
display: grid;
place-items: center;
}
<div id="parent"> parent -Only log 'parent' when green background is clicked and nothing else-
<div id="child1">child1 <br> -Nothing should happen when clicked-</div>
<div id="child2">child2 <br> -Should only log -child 2 if clicked-</div>
</div>
我尝试了stopPropagation(),但它可以阻止处理程序在冒泡时触发,所以我需要将它添加到所有子事件处理程序中,并且我仍然无法在单击对象时阻止父级触发事件监听器。
有没有办法只在单击元素本身时限制父处理程序?
【问题讨论】:
标签: javascript