本文介绍了如何让点击事件只在父 DIV 上触发,而不是在孩子上触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有分类的 foobar 的 DIV,以及该 DIV 中的一些未分类的 DIV,但我想它们继承了 foobar 类:
$('.foobar').on('click', function() {/*...做东西...*/});我希望它仅在点击 DIV 中的某处而不是其子 DIV 时触发.
解决方案如果 e.target 与 this 是相同的元素,则您没有点击后代.
$('.foobar').on('click', function(e) {if (e.target !== this)返回;alert('点击了foobar');});.foobar {填充:20px;背景:黄色;}跨度 {背景:蓝色;白颜色;填充:8px;}<script src="ajax.googleapis/ajax/libs/jquery/1.11.1/jquery.min.js"></script>.foobar(警报)<span>child(无警报)</span>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.
解决方案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 上触发,而不是在孩子上触发?
发布评论