我正在使用这段代码:

$('body').click(function() {
   $('.form_wrapper').hide();
});

$('.form_wrapper').click(function(event){
   event.stopPropagation();
});

这个HTML:

<div class="form_wrapper">
   <a class="agree" href="javascript:;">I Agree</a>
   <a class="disagree" href="javascript:;">Disagree</a>
</div>

问题是,我有链接在div和当他们不再工作时,点击。


当前回答

我在一个搜索框上工作,根据处理的关键字显示自动完成。当我不想点击任何选项,然后我将使用下面的代码隐藏处理的列表,它的工作。

$(document).click(function() {
 $('#suggestion-box').html("");
});

建议框是我的自动完成容器,我显示的值。

其他回答

var n = 0;
$("#container").mouseenter(function() {
n = 0;

}).mouseleave(function() {
n = 1;
});

$("html").click(function(){ 
if (n == 1) {
alert("clickoutside");
}
});

更新解决方案为:

使用mouseenter和mouseleave代替 的悬停使用活动事件绑定

var mouseOverActiveElement = false;

$('.active').live('mouseenter', function(){
    mouseOverActiveElement = true; 
}).live('mouseleave', function(){ 
    mouseOverActiveElement = false; 
});
$("html").click(function(){ 
    if (!mouseOverActiveElement) {
        console.log('clicked outside active element');
    }
});

通过使用这段代码,您可以隐藏尽可能多的项目

var boxArray = ["first element's id","second element's id","nth element's id"];
   window.addEventListener('mouseup', function(event){
   for(var i=0; i < boxArray.length; i++){
    var box = document.getElementById(boxArray[i]);
    if(event.target != box && event.target.parentNode != box){
        box.style.display = 'none';
    }
   }
})

我觉得这样会容易得多。我是这样做的:

$(':not(.form_wrapper)').click(function() {
    $('.form_wrapper').hide();
});

我在一个搜索框上工作,根据处理的关键字显示自动完成。当我不想点击任何选项,然后我将使用下面的代码隐藏处理的列表,它的工作。

$(document).click(function() {
 $('#suggestion-box').html("");
});

建议框是我的自动完成容器,我显示的值。