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

非 Y 不嫁゛ 提交于 2019-12-22 11:35:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!