Jquery - 隐藏在文档上的任何位置 [英] Jquery - hide on click anywhere on document

查看:113
本文介绍了Jquery - 隐藏在文档上的任何位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,只要你点击它之外就会隐藏,但是我有一些麻烦,在div内部的某些链接工作(而不是隐藏div)。

I have a div that hides whenever you click outside of it but I'm having some trouble getting certain links inside the div to work (and not hide the div).

$(document).click(function() {
    fav.hide();
});
theDiv.click(function(e) {
    e.stopPropagation();
});

这是我整个点击外面和关闭事件。亲爱的事情:我有两种类型的链接在我的div,一个常规链接,另一个是一个javascript。常规的一个重定向好,但是javascript没有做任何事情。

That is what I have for the whole clicking outside and closing event. Heres the thing: I have two types of links in my div, one regular link and another which is a javascript one. The regular one redirects OK but the javascript one doesn't do anything.

有人可以帮助我吗?谢谢。

Could somebody help me out? Thanks.

编辑:

以下是我的代码可能帮助

Here are the bits of my code that might help out

var fav = $('#favorites');

// Open & close button
$('#favorites_a').click(function(e) {
    e.stopPropagation();
    e.preventDefault();
    fav.toggle();
});

$('a.c',fav).live('click', function(e) {
    alert('hey');
});

$(document).click(function() {
    fav.hide();
});

fav.click(function(e) {
    e.stopPropagation();
});

HTML(在页面加载后构建):

HTML (built after page load):

<div id="favorites">
    <div class="wrap">
        <ul><li><a href="/abc" class="p">A</a><a href="#" class="c">B</a></li></ul>
    </div>
</div>


推荐答案

这可能是一个问题, live()点击事件处理程序。当您使用 live 时,事件处理程序实际上附加到文档。所以事件需要冒泡到文档中,但是您的点击事件处理程序 fav 可以防止冒泡。

This could be a problem with the live() click event handler. When you use live the event handler is actually attached to the document. So the event needs to bubble up to the document, but your click event handler on fav prevents bubbling up.

它可以与 委托 配合使用:

It works with delegate though:

fav.delegate('a.c', 'click', function(e) {
    alert('hey');
});

这里,事件处理程序添加到 fav

Here, the event handler is added to fav.

演示

这篇关于Jquery - 隐藏在文档上的任何位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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