我有这个按钮。我只是注意到,如果在两个嵌套元素上具有相同的类名,则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>
您需要防止传播,因为您的父/子具有相同的类,因此请使用 e.stopPropagation()
$('body').on('click', '.remove', e => {
e.stopPropagation()
$(e.currentTarget).hasClass('remove') ? console.log('test') : ''
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" rel="stylesheet" />
<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</i></button>
其他选择是使用 e.currentTarget()
$('body').on('click', '.remove', e => $(e.currentTarget).hasClass('remove') ? console.log('test') : '')
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" rel="stylesheet" />
<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</i></button>
这是JS纯解决方案
document.addEventListener('click', e => e.target.classList.contains('remove') ? console.log('test') : '')
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" rel="stylesheet" />
<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</i></button>
注意:因为您button
使用了type='button'
,所以无需使用e.preventDefault()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句