简体   繁体   English

jQuery Selector:选择一个框,但不选择框内的元素

[英]jQuery Selector : select a box but not an element inside the box

Let's says I have the following code : 假设我有以下代码:

<div class="body">
  Click me and it will work.
  <div class="head">Click me and nothing will happen.</div>
</div>

I want to display the "it works" when you click inside the .body div but not inside the .head div. 当您在.body div内而不是.head div内单击时,我想显示“有效”。 How can I do this? 我怎样才能做到这一点?

With this code, the log appears even if you click on head : 使用此代码,即使您单击head也会显示日志:

<script>
$('.body').click(function(){console.log('it works !');});
</script>
$('.body').click(function(e){

if($(e.target).hasClass('body'))
  console.log('it works !');

});

Event bubbling is causing your troubles. 事件冒泡引起您的麻烦。 Essentially, the event handler for your 'head' class would capture the click and then bubble that event up to your 'body' handler because there are nested. 本质上,您的“ head”类的事件处理程序将捕获单击,然后将该事件冒泡到您的“ body”处理程序中,因为其中有嵌套。

Here is an excellent primer on event bubbling, how it works, and how to control event bubbling. 这是有关事件冒泡,如何工作以及如何控制事件冒泡的出色入门。

Here is working jsFiddle example for you to test. 这是工作的jsFiddle示例,供您测试。

Its called event bubbling. 它称为事件冒泡。 When you click on "head" div you also click on "body" div. 当您单击“ head” div时,您也单击“ body” div。

You need to add: 您需要添加:

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

to prevent event bubbling. 防止事件冒泡。

This is the general solution: 这是一般的解决方案:

$('.body').click(function(e){
    if(e.target === this) {
        console.log('it works !');
    }
});

Solved similar question on stackoverflow: Select only parent, exclude everything else while click() 解决了关于stackoverflow的类似问题: 仅选择父项,而在click()时排除其他所有项

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

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