What would be the most sane way to attach an event to everything on the DOM?
Let me describe the thing that I want to accomplish: I basically want to make the 'inspect element' hover effect from Firebug, so a user can eventually select content from the DOM.
I started with a naive imple开发者_如何学运维mentation of:
$('div').bind('mouseover', function() {
$(this).css('border', '1px solid black');
}).bind('mouseleave', function() {
$(this).css('border', 'none');
});
This has several problems (some of which I can fix) but the immediate and most apparent is bubbling so that every parent <div>
gets a border, and also that it's only attached to <div>
s
Do I need to enumerate each element set that I want this event attached to? Do I need to prevent bubbling somehow so that only the upper-most element gets the event handler (and what does that look like?)
Any and all suggestions welcome!
$(document).bind('mouseover', function(event) {
$(event.target).addClass('hover');
});
This will attach one event handler to document
, and events will bubble up to it where they will be handled.
See it on jsFiddle.
精彩评论