admin管理员组

文章数量:1220003

I would like to fire an event when anything on the page is clicked, and then process normally. For example a click would be fired, I would see if the target matched something, alert if it did, and then have the click event continue (no preventDefault()).

I would like to fire an event when anything on the page is clicked, and then process normally. For example a click would be fired, I would see if the target matched something, alert if it did, and then have the click event continue (no preventDefault()).

Share Improve this question asked Jun 24, 2010 at 14:37 Josh KJosh K 28.9k20 gold badges88 silver badges132 bronze badges 1
  • If you click something, it will match something - unless you really meant "match some specific thing" – Mark Schultheiss Commented Jun 24, 2010 at 21:32
Add a comment  | 

3 Answers 3

Reset to default 15
$(document).click(function(e) {
    // e.target is the element which has been clicked.
});

This will handle all click events unless a handler prevents the event from bubbling up (by calling the stopPropagation() method of the event object).

$("body").click(function (event) {
// Your stuff here
}

3 options for you:

This is how .live() in jquery works. Everything bubbles to the top, and it matches the selector you set. http://api.jquery.com/live/

A more efficient way to do it is using .delegate, or providing a context to .live() so you don't have to bubble to the top. http://api.jquery.com/delegate/

If you want to do it manually, bind 'click' to the document, and use .closest() to find the closest matching selector: http://api.jquery.com/closest/

It's all the same concept, event delegation as mentioned already.

本文标签: javascriptGlobal jQuery click()Stack Overflow