【问题标题】:Stop parent event handler without editing all child event handlers停止父事件处理程序而不编辑所有子事件处理程序
【发布时间】: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


    【解决方案1】:

    检查 .target 是否是父级 - 如果是,则表示点击是直接在父级上进行的,而不是从子级冒泡的事件。

    const parent = document.getElementById('parent');
    parent.addEventListener('click', (e) => {
      if (e.target === parent) {
        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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      相关资源
      最近更新 更多