我在监听器 jquery 中使用,我想要一些东西 $(".parentClass:not(.childClass)").on("click",function(){}),但是当我点击 child 时这段代码不起作用div 监听器已运行,我只想运行父级;
最佳答案
您可以使用 event.stopPropagation()
用于阻止父事件处理程序操作
// Handler for parent
$(".parentClass").on("click", function(e) {
alert('hi')
});
// Handler for child
$('.childClass').click(function(e) {
e.stopPropagation();
// preventing any parent handlers action
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parentClass">
parent1
<div class="childClass">
child
</div>
</div>
event.stopPropagation()
: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
关于javascript - 选择一个元素而不选择父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32548400/