问题
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