如何点击事件只能在父DIV上点火,而不是孩子? [英] How to have click event ONLY fire on parent DIV, not children?

查看:146
本文介绍了如何点击事件只能在父DIV上点火,而不是孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分类为 foobar 的DIV,以及DIV中的几个DIV,这些DIV是未分类的,但我想他们是继承 foobar class:

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...*/ });

我想要点击DIV中的某个地方但不是其子节点DIV。 / p>

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

推荐答案

如果 e.target 这个,你没有点击后代。

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>

这篇关于如何点击事件只能在父DIV上点火,而不是孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆