【发布时间】:2021-02-27 12:41:41
【问题描述】:
我有这个按钮。我刚刚注意到,如果我在两个嵌套元素上具有相同的类名,click 侦听器将触发两次。当我点击时,我该如何解决这个问题?
$('body').on('click', '.remove', function(e) {
e.preventDefault();
if ($(e.target).hasClass('remove')) {
console.log('test'); //executed twice here
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn remove "><i class="fas fa-trash remove">Remove icon</i></button>
【问题讨论】:
-
发生这种情况是因为您在 .remove 类上设置了单击事件,并且该按钮具有该类的 2 个元素。一个是按钮本身,另一个是 标签。您需要使用 e.stopPropagation() 来停止从 i 到按钮的事件传播。
标签: javascript html jquery dom-events