Javascript 捕获使用 jQuery 执行的任何点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3277386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Catching any click performed using jQuery
提问by RadiantHex
the noob way to do it I guess would be
做这件事的菜鸟方法我想是
$('*').click(function(){...});
But is there any way I can catch any type of click, without having to register a listener for every object in the DOM?
但是有什么方法可以捕获任何类型的点击,而不必为 DOM 中的每个对象注册一个监听器?
Help would be amazing. =)
帮助将是惊人的。=)
回答by Nick Craver
A clickevent will by default bubble up the DOM, so you can just attach a clickhandler to the root, like this:
一个click事件将默认冒泡的DOM,所以你可以附加一个click处理程序的根,就像这样:
$(document).click(function() {
//do something
});
Unless a handler on an element along the way does an event.stopPropagation()or return false, you'll get the click here.
除非沿途元素上的处理程序执行event.stopPropagation()或return false,否则您将在此处获得单击。
回答by Vincent Robert
You can use event delegation on the document to catch all clicks.
您可以在文档上使用事件委托来捕获所有点击。
jQuery will fill the targetproperty of the eventto retrieve the clicked element.
jQuery 将填充 的target属性event以检索单击的元素。
$(document).click(function(event){
// event.target is the clicked object
});
Note that event.targetwill be the deepest element clicked. Ex: if there is a <span>in a <a>, you will get the <span>, not the <a>.
请注意,这event.target将是点击最深的元素。例如:如果 a<span>中有 a <a>,您将得到<span>,而不是<a>。
If you want to catch any click but want to retrieve a specific element (like a class), you can do:
如果您想捕捉任何点击但想要检索特定元素(如类),您可以执行以下操作:
$(document).click(function(event){
$(event.target).closest(".clickable").each(function(){
// "this" is your "clickable" clicked
});
});
Unless an event handler on an element along the way does an event.stopPropagation()or return false, you'll get the click here.
除非沿途元素上的事件处理程序执行event.stopPropagation()或return false,否则您将在此处获得点击。
回答by jasongetsdown
$('*').click( function() {...} )will only catch clicks on elements that existed when you made the call to .click(). To catch clicks on elements that may be created later you will need to bind to bodyor documentas others have suggested.
$('*').click( function() {...} )只会捕获对调用时存在的元素的点击.click()。要捕捉可能稍后创建的元素的点击,您需要绑定到body或document按照其他人的建议。
回答by Mottie
How about just attaching a click to the body?
只在身体上附加一个咔嗒声怎么样?
$('body').click(function(e){ ... })
The e.targetshould contain what was clicked on
本e.target应包含的内容被点击
回答by pkaeding
How about:
怎么样:
$('body').click(function(){...});
Any click will be on the body, since that is the parent of all visible nodes in the dom.
任何点击都会在 body 上,因为它是 dom 中所有可见节点的父节点。

