我正在使用这段代码:

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


当前回答

根据prc322的精彩答案构建。

function hideContainerOnMouseClickOut(selector, callback) {
  var args = Array.prototype.slice.call(arguments); // Save/convert arguments to array since we won't be able to access these within .on()
  $(document).on("mouseup.clickOFF touchend.clickOFF", function (e) {
    var container = $(selector);

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
      container.hide();
      $(document).off("mouseup.clickOFF touchend.clickOFF");
      if (callback) callback.apply(this, args);
    }
  });
}

这增加了一些东西……

放置在带有“unlimited”参数的回调函数中 添加了对jquery的.off()的调用,与事件名称空间配对,以便在事件运行后将其从文档中解绑定。 包括触摸端移动功能

我希望这能帮助到一些人!

其他回答

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

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

遇到同样的问题,就想出了这个简单的解决方法。它甚至可以递归工作:

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

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

var exclude_div = $("#ExcludedDiv");; 美元(文档).click(函数(e) { 如果(! exclude_div。Is (e.target)) //如果目标div不是一个你想排除然后添加类隐藏 $ (" .myDiv1 ") .addClass(“隐藏”); });

小提琴

将点击事件附加到表单包装器外的顶级元素,例如:

$('#header, #content, #footer').click(function(){
    $('.form_wrapper').hide();
});

这也适用于触摸设备,只是要确保你的选择器列表中没有包含.form_wrapper的父类。

如果你点击.form_wrapper返回false:

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

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