在外部单击时使用jQuery隐藏DIV,但允许传播事件 [英] Use jQuery to hide DIV when click outside it, but allow propagation of events

查看:109
本文介绍了在外部单击时使用jQuery隐藏DIV,但允许传播事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了许多其他问题,包括在单击div时如何关闭div,但是我遇到了一个复杂的问题,因为我还有其他与.live()绑定的元素

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()

我想发生的事情是,如果我单击页面上的其他任何位置,div应该会消失,包括单击实时"元素.当我单击该实时元素时,我希望它的处理程序能够正常进行.

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.

据我所知,处理关闭div的基本方法是将click侦听器附加到或$ document,但这将防止任何其他实时事件冒泡通过上述body/doc处理程序.有没有解决的办法?

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?

推荐答案

在现场,事件按顺序从最前端爬到最后端.在活动"元素的单击(这是主体对象的直接/间接子项)中,如果不返回false或停止传播,它将使梯形图上升以到达文档的单击处理程序.通过实时附加文档的点击似乎无效.

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.

在此处检查示例实现: http://jsfiddle.net/VHtSP/6/

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

这篇关于在外部单击时使用jQuery隐藏DIV,但允许传播事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆