我有一个带有分类 foobar
的 DIV,以及该 DIV 中的一些未分类的 DIV,但我想它们继承了 foobar
类:
$('.foobar').on('click', function() { /*...do stuff...*/ });
我希望它仅在单击 DIV 中的某处而不是其子 DIV 时触发。
最佳答案
如果 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>
关于jquery - 如何让点击事件只在父 DIV 上触发,而不是在子 DIV 上触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9183381/