我有一个包含多个子元素的父元素,其中一些有自己的事件监听器,而另一些则没有。父元素具有单击处理程序,我只想在单击父元素本身而不是任何子元素时运行它。
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()
,它可以阻止事件冒泡,但我需要将它添加到所有子事件处理程序中,但我仍然无法阻止父事件在以下情况下触发单击没有事件监听器的对象。
有没有办法只在点击元素本身时限制父处理程序?
最佳答案
event.currentTarget
可能有助于验证事件是否来自您设置事件的特定元素,而不是来自子元素。来自 MDN 的 documentation 的快速定义:
The
currentTarget
read-only property of theEvent
interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed toEvent.target
, which identifies the element on which the event occurred and which may be its descendant.
以及在@CertainPerformance 的 solution 上这样做的优势(这很棒)是您不必知道该元素。
document.getElementById('parent').addEventListener('click', (e)=> {
if(e.currentTarget===e.target){
console.log('parent clicked');
}
});
document.getElementById('child2').addEventListener('click', (e)=> {
if(e.currentTarget===e.target){
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>
关于javascript - 在不编辑所有子事件处理程序的情况下停止父事件处理程序表单触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72670183/