简体   繁体   English

jQuery事件-如何选择整个DIV,但不包括某些内部区域

[英]Jquery event - how to select entire DIV excluding some inner area

Think of the following HTML code to apply Jquery: 考虑以下HTML代码以应用Jquery:

HTML code: HTML代码:

<div id="outer_div">
  <div id="inner_div_1"></div>
  <div id="inner_div_2"></div>
  <div id="inner_div_3"></div>
</div>

By default, the "outer_div" is hidden. 默认情况下,“ outer_div”是隐藏的。 It appears while clicked on a button using Jquery show() function. 使用Jquery show()函数单击按钮时显示。 I wanted to do the following: On click within anywhere of "outer_div" excluding the area within "inner_div_1" , the "outer_div" would again be hidden. 我想执行以下操作:单击“ outer_div”中除“ inner_div_1”内的区域之外的任何位置时,“ outer_div”将再次被隐藏。 I failed while tried the following codes. 我尝试以下代码时失败。 What should I amend? 我应该修改什么?

Attempted Jquery 1: 尝试使用jQuery 1:

$("#outer_div:not(#inner_div_1)").on("click",function(){
    $("#outer_div").hide("slow");
});

Attempted Jquery 2: 尝试使用jQuery 2:

$("#outer_div").not("#inner_div_1").on("click",function(){
    $("#outer_div").hide("slow");
});

Your support would be highly appreciated. 非常感谢您的支持。

You need to consider that a click in the inner div is also a click on the outter div. 您需要考虑的是,在内部div上单击也是在外部div上单击。 That being said, you just need to check the target and target parents : 话虽如此,您只需要检查目标父母和目标父母即可:

$("#outer_div").on("click",function(e){
    if(!$(e.target).closest('#inner_div_1').length) $("#outer_div").hide("slow");
});

You can use some of the data in the event 您可以在事件中使用一些数据

$("#outer_div").on("click",function(e){
    if( // Fast check to see if this is the div
        e.target.id !=='inner_div_1'
        // We limit the 'closest()' code to the outer div. This adds children to the exclude
        && $(this).closest('#inner_div_1, #outer_div')[0].id=='outer_div'){
        alert('good click');
    }
});

This is a solution for your code now, this works perfect when not too many excluding objects. 现在这是您的代码的解决方案,当没有太多排除对象时,此方法非常理想。 But no wildcard selectors, which is nice. 但是没有通配符选择器,这很好。
And a jsFiddle demo . 还有一个jsFiddle演示


Other properties can be used to, like a class: 可以使用其他属性,例如类:

$("#outer_div").on("click",function(e){
    if( e.target.className!=='even' 
        && $(this).closest('.even, #outer_div')[0].id=='outer_div'){
        alert('yay, clicked an odd');
    }
});

I made 7 lines, gave the even ones a class 'even' . 我写了7行,给偶数课“ even”

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

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