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

编程入门 行业动态 更新时间:2024-10-08 05:21:42
本文介绍了如何让点击事件只在父 DIV 上触发,而不是在子 DIV 上触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个带有分类 foobar 的 DIV,以及该 DIV 中的一些未分类的 DIV,但我想它们正在继承 foobar 类:

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 时触发.

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

推荐答案

如果 e.target 和 this 是同一个元素,那么你没有点击过后代.

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="ajax.googleapis/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class='foobar'> .foobar (alert) <span>child (no alert)</span> </div>

更多推荐

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

本文发布于:2023-11-28 06:27:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641295.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是在   而不   只在   事件   DIV

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!