简体   繁体   English

如何在jQuery中单击子元素而不是单击父元素?

[英]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 单击特定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/ 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. 单击红色div之外的任何位置应使其隐藏。 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. 现在,跨度的点击也被视为对父div的点击,因此,如果单击跨度,它不会隐藏div。

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/ 演示: 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/ 这是您更新的工作提琴: 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/ 现场演示: http //jsfiddle.net/uMLrC/

So this 所以这

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

caches the reference to the DIV element. 缓存对DIV元素的引用。 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. 而且它还提高了代码的可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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