我正在使用这段代码:

$('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和当他们不再工作时,点击。


当前回答

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

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

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

其他回答

摘自https://sdtuts.com/click-on-not-specified-element/

现场演示http://demos.sdtuts.com/click-on-specified-element

$(document).ready(function () {
    var is_specified_clicked;
    $(".specified_element").click(function () {
        is_specified_clicked = true;
        setTimeout(function () {
            is_specified_clicked = false;
        }, 200);
    })
    $("*").click(function () {
        if (is_specified_clicked == true) {
//WRITE CODE HERE FOR CLICKED ON OTHER ELEMENTS
            $(".event_result").text("you were clicked on specified element");
        } else {
//WRITE CODE HERE FOR SPECIFIED ELEMENT CLICKED
            $(".event_result").text("you were clicked not on specified element");
        }
    })
})

这段代码检测页面上的任何单击事件,然后当且仅当所单击的元素既不是#CONTAINER元素也不是它的后代元素时,隐藏#CONTAINER元素。

$(document).on('click', function (e) {
    if ($(e.target).closest("#CONTAINER").length === 0) {
        $("#CONTAINER").hide();
    }
});

这么多答案我都用不上。相反,我采取了公认的答案(工作得很好),并缩短为以下(使用后代选择器):

$(document).mouseup(function(e) 
{
    if (!$(e.target).is("#targetSelector,#targetSelector *")) {
        $('#targetSelector').hide();
    }
});

因为它只以用户交互的速度运行,没有给变量赋值

这么多答案,加一个肯定是一种通行权… 我没有看到当前(jQuery 3.1.1)的答案-所以:

$(function() {
    $('body').on('mouseup', function() {
        $('#your-selector').hide();
    });
});

这个解决方案应该工作得很好,很简单:

jQuery(document).ready(function($) {
    jQuery(document).click(function(event) {
        if(typeof  jQuery(event.target).attr("class") != "undefined") {
            var classnottobeclickforclose = ['donotcountmeforclickclass1', 'donotcountmeforclickclass2','donotcountmeforclickclass3'];
            var arresult = jQuery.inArray(jQuery(event.target).attr("class"), classnottobeclickforclose);
            if (arresult < 0) {
                jQuery(".popup").hide();
            }
        }
    });
});

在上面的代码更改donotcountmeforclickclass1, donotcountmeforclickclass2等类,你已经用来显示弹出或在它的点击弹出不应该影响,所以你必须明确添加类,你正在使用打开弹出。

用popup class更改.popup class。