javascript - 在不编辑所有子事件处理程序的情况下停止父事件处理程序表单触发

标签 javascript html

我有一个包含多个子元素的父元素,其中一些有自己的事件监听器,而另一些则没有。父元素具有单击处理程序,我只想在单击父元素本身而不是任何子元素时运行它。

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 the Event 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 to Event.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/

相关文章:

javascript - 输入更改时从一组输入中删除内容

html - 使列默认占用最少的空间 - Foundation Responsive Tables

javascript - 我在输入类型文件中的 onChange 之后得到未命名状态 - ReactJS

javascript - 每次运行函数时如何将对象添加到数组中?

javascript - Ajax 提交表单时收到 400 Bad Request

javascript - 根据选择选项更改属性

javascript - JMeter 持续时间断言覆盖响应代码

javascript - ES6 函数中 while 循环中的解构赋值不会在循环外传播?

javascript - 在不知道键名的情况下获取键的值

html - 在 flexbox div 而不是浏览器窗口上渲染滚动条