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

发布于 2025-01-03 13:44:26 字数 224 浏览 1 评论 0原文

我有一个带有分类 foobar 的 DIV,以及该 DIV 内的一些未分类的 DIV,但我认为它们继承了 foobar 类:

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

我希望它能够启动仅当单击 DIV 中的某处而不是其子 DIV 时。

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 foobar class:

$('.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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

糖果控 2025-01-10 13:44:27

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

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

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

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)

情感失落者 2025-01-10 13:44:27
$(".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
})
$(".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
})
奶气 2025-01-10 13:44:27

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

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

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

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

葬花如无物 2025-01-10 13:44:27

如果您无法使用 pointer-events: none; 并且面向现代浏览器,您可以使用 composedPath 来检测对对象的直接点击,如下所示:

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

您可以阅读更多关于这里的composedPath:
https://developer.mozilla.org/en-US/文档/Web/API/Event/composedPath

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

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

柏林苍穹下 2025-01-10 13:44:27

当你定义一个事件时,该事件有一个属性this。该属性表示事件被分配到的 DOMElement。要检查触发事件的元素,请使用 e.target

由于事件是在元素的子元素中继承的,因此检查目标是否

function doSomething(event) {
  if (this == event.target){
    // do something
  }
}

When you define an event, the event has a property this. This property represents the DOMElement to which the event was assigned.To check the element in which the event was fired, use e.target.

Since events are inherited in the children of an element, check if the target

function doSomething(event) {
  if (this == event.target){
    // do something
  }
}
七禾 2025-01-10 13:44:27

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

查找父案例

$(".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'
});

查找子案例

$(".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'
});

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

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'
});
萌面超妹 2025-01-10 13:44:27
// if its li get value 
document.getElementById('li').addEventListener("click", function(e) {
                if (e.target == this) {
                    UodateNote(e.target.id);
                }
                })
                
                
                function UodateNote(e) {

    let nt_id = document.createElement("div");
    // append container to duc.
    document.body.appendChild(nt_id);
    nt_id.id = "hi";
    // get conatiner value . 
    nt_id.innerHTML = e;
    // body...
    console.log(e);

}
li{
 cursor: pointer;
    font-weight: bold;
  font-size: 20px;
    position: relative;
    width: 380px;
    height: 80px;
    background-color: silver;
    justify-content: center;
    align-items: center;
    text-align: center;
    margin-top: 0.5cm;
    border: 2px solid purple;
    border-radius: 12%;}
    
    p{
     cursor: text;
  font-size: 16px;
   font-weight: normal;
    display: block;
    max-width: 370px;
    max-height: 40px;
    overflow-x: hidden;}
<li id="li"><p>hi</p></li>

// if its li get value 
document.getElementById('li').addEventListener("click", function(e) {
                if (e.target == this) {
                    UodateNote(e.target.id);
                }
                })
                
                
                function UodateNote(e) {

    let nt_id = document.createElement("div");
    // append container to duc.
    document.body.appendChild(nt_id);
    nt_id.id = "hi";
    // get conatiner value . 
    nt_id.innerHTML = e;
    // body...
    console.log(e);

}
li{
 cursor: pointer;
    font-weight: bold;
  font-size: 20px;
    position: relative;
    width: 380px;
    height: 80px;
    background-color: silver;
    justify-content: center;
    align-items: center;
    text-align: center;
    margin-top: 0.5cm;
    border: 2px solid purple;
    border-radius: 12%;}
    
    p{
     cursor: text;
  font-size: 16px;
   font-weight: normal;
    display: block;
    max-width: 370px;
    max-height: 40px;
    overflow-x: hidden;}
<li id="li"><p>hi</p></li>

小女人ら 2025-01-10 13:44:27
$('.foobar').on('click', function(e) {
  var el = e.target;
  if (e.target !== this) {
    el = e.target.closest('DIV');
  }

  // do stuff with el
});
$('.foobar').on('click', function(e) {
  var el = e.target;
  if (e.target !== this) {
    el = e.target.closest('DIV');
  }

  // do stuff with el
});
独孤求败 2025-01-10 13:44:26

如果 e.targetthis 是相同的元素,则您没有点击后代。

$('.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>

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

$('.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>

花辞树 2025-01-10 13:44:26

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

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

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

if(e.target !== e.currentTarget) return;
爺獨霸怡葒院 2025-01-10 13:44:26

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

pointer-events: none;

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

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

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

pointer-events: none;

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

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

2025-01-10 13:44:26

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

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

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();
});
可遇━不可求 2025-01-10 13:44:26
//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)
});

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

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

//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 click event on any of the children element(s) of the .foobar element(s) so the event won't reach the .foobar element(s) to fire their event handler(s).

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文