仅在单击元素时触发事件,而不在其子元素上触发事件 [英] Fire event only when clicking on an element, and not on its children

查看:74
本文介绍了仅在单击元素时触发事件,而不在其子元素上触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将单击处理程序绑定到正文元素,当我点击页面上的任何内容时,事件是触发。我可以在每次点击时检查 event.target

If i bind a click handler to the body element, when i click anything on the page the event is triggered. I can check the event.target on every click:

$("body").on("click", function(event) {
  if (event.target.tagName == "BODY") {
    ...
  }
});

但这似乎有点矫枉过正。有没有办法只在单击身体本身的空白区域时触发事件?

but that seem a bit overkill. Is there a way to trigger the event only when clicking the blank area of the body itself?

推荐答案

你可以使用 eventPhase 事件属性。值 2 表示该事件当前正在触发目标元素:

You can use the eventPhase property of event. A value of 2 means that the event is currently triggering the target element:

$("body").on("click", function(event) {
    //Cancel if not at target
    if (event.eventPhase != 2) return;

    //Other Code Here
});

小提琴: http ://jsfiddle.net/o0yptmmp/

这篇关于仅在单击元素时触发事件,而不在其子元素上触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆