简体   繁体   中英

How to make a click on a child element not be considered a click on it's parent in jQuery?

The question of how to detect a click on anywhere except a specified element has been answered a couple of items like here:

Event on a click everywhere on the page outside of the specific div

The problem I have is trying to figure out how to detect a click anywhere except a given element including one of it's children.

For example in this code:

http://jsfiddle.net/K5cEm/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(function() {

$(document).click(function(e) {
   $('#somediv').hide();
});
$('#somediv').click(function(e) {
   e.stopPropagation();
});

});
</script>

<div style="border: 1px solid red; width:100px; height: 100px" id="somediv">

    <span style="display: block; border: 1px solid green; width:50px; height: 50px; margin: 0 auto" id="someSpan"></span>

</div>

Clicking anywhere outside the red div should cause it to hide. Not only that but also clicking on it's child element (the green span) should cause it to hide. The only time it shouldn't hide is if you click on it but not on the span. As it stands now, the click on the span is also considered a click on the parent div hence it doesn't hide the div if the span is clicked.

How to achieve this?

You can compare the click's target to the element in question:

$(document).click(function(e) {
    if (e.target != $('#somediv')[0]) {
        $('#somediv').hide();
    }
});

Demo: http://jsfiddle.net/K5cEm/7/

Add this:

$('#somediv').click(function(e) {
    e.stopPropagation();
}).children().click(function(e) {
    $('#somediv').hide();
});

Here's your updated working fiddle: http://jsfiddle.net/K5cEm/5/

I'd do it like so:

$(function () {
    var elem = $( '#somediv' )[0];

    $( document ).click( function ( e ) {
        if ( e.target !== elem ) {
            $( elem ).hide();
        }
    });
});

Live demo: http://jsfiddle.net/uMLrC/

So this

var elem = $( '#somediv' )[0];

caches the reference to the DIV element. We want to cache this reference on page load, so that we don't have to query for that element repeatedly. And it improves the readability of the code, also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM