问题
I've read a lot of the other questions involving how to close a div when you click outside of it, but I have a compounded problem in that I have other elements that are bound with .live()
What I want to happen is that if I click anywhere else on the page the div should disappear, including if I click on a 'live' element. When I click on that live element I want it's handler to proceed normally.
So far as I've read, the basic way to handle closing the div is to attach a click listener to the or $document, but this would prevent any other live event from bubbling past the aforementioned body/doc handler. Is there a way around this?
回答1:
In live, events bubble up the ladder from front-most to back-most in that order. In your 'live' element's click (which is a direct/indirect child of your body object), if you don't return false or stop propagation, it will bubble up the ladder to reach the document's click handler. Attaching the document's click via live doesn't seem to work.
Check sample implementation here: http://jsfiddle.net/VHtSP/6/
$('div.menu').live('click', function(e) {
e.stopPropagation();
alert('click inside menu. will not propagate.');
return false;
});
$(document).click(function() {
alert('document click() handler.');
// close the div
$('div.menu').hide();
});
$('a').live('click', function() {
alert('<a> click() handler');
// .. your code to handle the live element's click
});
来源:https://stackoverflow.com/questions/7264483/use-jquery-to-hide-div-when-click-outside-it-but-allow-propagation-of-events