我正在使用这段代码:

$('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).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();
    }
});

其他回答

这样不行吗?

$("body *").not(".form_wrapper").click(function() {

});

or

$("body *:not(.form_wrapper)").click(function() {

});

var $container = $("#popup_container"); $container.click(function(e) { if (e.target.id == $container.attr("id")) { $(this).hide(); } }); #popup_container { background: rgba(200,200,200,0.6); width: 100vh; height: 100vh; position: fixed; display: flex; justify-content: center; align-items: center; } #popup { background: yellow; border: 1px solid black; position: absolute; width: 50%; height: 50%; display: flex; justify-content: center; align-items: center; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="popup_container"> <div id="popup"> Popup </div> </div>

https://jsfiddle.net/041pj7re/

摘自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");
        }
    })
})
$(document).click(function(event) {
    if ( !$(event.target).hasClass('form_wrapper')) {
         $(".form_wrapper").hide();
    }
});

对于像IPAD和IPHONE这样的触摸设备,我们可以使用下面的代码

$(document).on('touchstart', function (event) {
var container = $("YOUR 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();
    }
});