【问题标题】:How to capture the most exterior element when click event occurs点击事件发生时如何捕获最外部的元素
【发布时间】:2021-09-29 16:50:47
【问题描述】:

在一个div中点击时需要获取最多的元素...比如这个...

 <div id="show_trash_id" class="switch switch-xs">
   <input type="checkbox"/>
   <span class="slider round">
     <span class="text-on">ON</span>
     <span class="text-off">OFF</span>
   </span>
 </div>

我认为这与某种冒泡或捕获效果有关。但是我无法处理...我已经尝试过 event.stopPropagation() 或使用 useCature 均未成功。

function capture (event) {
   event.stopPropagation();
   console.log(event.target);
}
document.querySelector('#show_trash_id').addEventListener('click', capture, true) 

简而言之,我想要在控制台中显示以下波纹管:

     <div id="show_trash_id" class="switch switch-xs">
       <input type="checkbox"/>
       <span class="slider round">
         <span class="text-on">ON</span>
         <span class="text-off">OFF</span>
       </span>
     </div>

【问题讨论】:

  • 你可以使用console.log(event.currentTarget)
  • 这正是我们需要的...谢谢@AlphaHowl
  • 哦,我开始使用内置的 event 方法写一个答案,但如果你不需要它,我想我会停止 :)

标签: javascript click addeventlistener event-bubbling event-capturing


【解决方案1】:

我以前也遇到过这个问题。我的解决方案一直是使用匿名函数并使用this 关键字而不是event.target,因为它指的是添加事件侦听器的元素。

但是请注意,匿名函数不能是箭头函数,因为箭头函数上下文中的this 是窗口。

document.querySelector('#show_trash_id').addEventListener('click', function(e) {
  console.log(this);
});
 <div id="show_trash_id" class="switch switch-xs">
   <input type="checkbox"/>
   <span class="slider round">
     <span class="text-on">ON</span>
     <span class="text-off">OFF</span>
   </span>
 </div>

【讨论】:

    猜你喜欢
    • 2014-10-18
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    相关资源
    最近更新 更多