开发者

Use jQuery to hide DIV when click outside it, but allow propagation of events

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 n开发者_高级运维ormally.

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?


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
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜