我正在使用这段代码:

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


当前回答

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

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

其他回答

(只是添加到prc322的答案。)

在我的例子中,我使用这段代码来隐藏当用户单击适当的选项卡时出现的导航菜单。我发现添加一个额外的条件很有用,即容器外的点击目标不是链接。

$(document).mouseup(function (e)
{
    var container = $("YOUR CONTAINER SELECTOR");

    if (!$("a").is(e.target) // if the target of the click isn't a link ...
        && !container.is(e.target) // ... or the container ...
        && container.has(e.target).length === 0) // ... or a descendant of the container
    {
        container.hide();
    }
});

这是因为我网站上的一些链接为页面添加了新内容。如果在添加新内容的同时导航菜单消失了,用户可能会迷失方向。

摘自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");
        }
    })
})

甚至溶化:

$("html").click(function(){ 
    $(".wrapper:visible").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。

根据文档,.blur()不仅仅适用于<input>标记。例如:

$('.form_wrapper').blur(function(){
   $(this).hide();
});