jQuery 如何让点击事件只在父 DIV 上触发,而不是在孩子上触发?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9183381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:28:48  来源:igfitidea点击:

How to have click event ONLY fire on parent DIV, not children?

jqueryeventsonclick

提问by CaptSaltyHyman

I have a DIV with a classed foobar, and a few DIVs inside that DIV that are unclassed, but I suppose they are inheriting the foobarclass:

我有一个带有foobarclassed 的 DIV,并且该 DIV 中有一些未分类的DIV,但我想它们继承了foobar该类:

$('.foobar').on('click', function() { /*...do stuff...*/ });

I want that to fire off only when clicking somewhere in the DIV but not on its children DIVs.

我希望它仅在单击 DIV 中的某处而不是其子 DIV 时触发。

回答by

If the e.targetis the same element as this, you've not clicked on a descendant.

如果e.target与 元素相同this,则您没有单击后代。

$('.foobar').on('click', function(e) {
  if (e.target !== this)
    return;
  
  alert( 'clicked the foobar' );
});
.foobar {
  padding: 20px; background: yellow;
}
span {
  background: blue; color: white; padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='foobar'> .foobar (alert) 
  <span>child (no alert)</span>
</div>

回答by hobberwickey

There's another way that works if you don't mind only targeting newer browsers. Just add the CSS

如果您不介意只针对较新的浏览器,还有另一种方法。只需添加 CSS

pointer-events: none;

to any children of the div you want to capture the click. Here's the support tables

到要捕获点击的 div 的任何子级。这是支持表

http://caniuse.com/#feat=pointer-events

http://caniuse.com/#feat=pointer-events

回答by ori

You can use bubbling in your favor:

您可以使用冒泡对您有利:

$('.foobar').on('click', function(e) {
    // do your thing.
}).on('click', 'div', function(e) {
    // clicked on descendant div
    e.stopPropagation();
});

回答by Jens T?rnell

I did not get the accepted answer to work, but this seems to do the trick, at least in vanilla JS.

我没有得到公认的工作答案,但这似乎可以解决问题,至少在 vanilla JS 中是这样。

if(e.target !== e.currentTarget) return;

回答by Jasper

//bind `click` event handler to the `.foobar` element(s) to do work,
//then find the children of all the `.foobar` element(s)
//and bind a `click` event handler to them that stops the propagation of the event
$('.foobar').on('click', function () { ... }).children().on('click', function (event) {
    event.stopPropagation();
    //you can also use `return false;` which is the same as `event.preventDefault()` and `event.stopPropagation()` all in one (in a jQuery event handler)
});

This will stop the propagation (bubbling) of the clickevent on any of the children element(s) of the .foobarelement(s) so the event won't reach the .foobarelement(s) to fire their event handler(s).

这将停止click事件在元素的任何子元素上的传播(冒泡),.foobar因此事件不会到达.foobar元素以触发其事件处理程序。

Here is a demo: http://jsfiddle.net/bQQJP/

这是一个演示:http: //jsfiddle.net/bQQJP/

回答by Michalis

$(".advanced ul li").live('click',function(e){
    if(e.target != this) return;
    //code
    // this code will execute only when you click to li and not to a child
})

回答by Wonx2150

I had the same problem and came up with this solution (based on the other answers)

我遇到了同样的问题并提出了这个解决方案(基于其他答案)

 $( ".newsletter_background" ).click(function(e) {
    if (e.target == this) {
        $(".newsletter_background").hide();
    } 
});

Basically it says if the target is the div then run the code otherwise do nothing (don't hide it)

基本上它说如果目标是 div 然后运行代码否则什么都不做(不要隐藏它)

回答by Wukadin

My case is similar but this is occasion when you have few foobar-s, and you want to close only one - per one click:

我的情况是类似的,但这是当你有几个foobar-s 并且你只想关闭一个 - 一次点击的时候:

Find parent case

查找父案例

$(".foobar-close-button-class").on("click", function () {
    $(this).parents('.foobar').fadeOut( 100 );
    // 'this' - means that you finding some parent class from '.foobar-close-button-class'
    // '.parents' -means that you finding parent class with name '.foobar'
});

Find child case

查找子案例

$(".foobar-close-button-class").on("click", function () {
    $(this).child('.foobar-close-button-child-class').fadeOut( 100 );
    // 'this' - means that you finding some child class from '.foobar-close-button-class'
    // '.child' -means that you finding child class with name '.foobar-close-button-child-class'
});

回答by Dejan Markovic

You can use event.currentTarget. It will do click event only elemnt who got event.

您可以使用 event.currentTarget。它只会做点击事件的元素谁得到事件。

target = e => {
    console.log(e.currentTarget);
  };
<ul onClick={target} className="folder">
      <li>
        <p>
          <i className="fas fa-folder" />
        </p>
      </li>
    </ul>

回答by Xenxier

If you can't use pointer-events: none;and are targeting modern browsers you can use composedPathto detect a direct click on the object like so:

如果您不能使用pointer-events: none;并且针对的是现代浏览器,您可以使用它composedPath来检测对对象的直接点击,如下所示:

element.addEventListener("click", function (ev) {
    if (ev.composedPath()[0] === this) {
        // your code here ...
    }
})

You can read more about composedPath here: https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath

您可以在此处阅读有关合成路径的更多信息:https: //developer.mozilla.org/en-US/docs/Web/API/Event/composedPath