Fire event only when clicking on an element, and not on its children

六眼飞鱼酱① 提交于 2019-12-22 00:24:03

问题


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?


回答1:


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
});

Fiddle Here: http://jsfiddle.net/o0yptmmp/




回答2:


You can do it if you check on every click if the element clicked has a body parent. If the condition is false, you are clicking the body:

$("body").on("click", function(event) {
  if ($(this).parents('body').length == 0) {
     //Do something
  }
});

In my opinion it's not a good practice, but it depends on your code and project.

Hope it helps.

Cheers.




回答3:


You should put an

event.stopPropagation()

on all children you want to not bubble up.

jQuery Docs: http://api.jquery.com/event.stoppropagation/.



来源:https://stackoverflow.com/questions/26150500/fire-event-only-when-clicking-on-an-element-and-not-on-its-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!