jQuery 为两个具有相同 class 名称的嵌套元素触发两次
jQuery fires twice for two nested elements with the same class name
我有这个按钮。我刚刚注意到,如果我在两个嵌套元素上使用相同的 class 名称,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>
你需要防止传播,因为你有 parent/child 和相同的 class,所以使用 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>
这里是纯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" />
<button type="button" class="btn remove"><i class="fas fa-trash remove">remove</i></button>
注意:因为你有button
和type='button'
,所以没必要用e.preventDefault()
我有这个按钮。我刚刚注意到,如果我在两个嵌套元素上使用相同的 class 名称,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>
你需要防止传播,因为你有 parent/child 和相同的 class,所以使用 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>
这里是纯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" />
<button type="button" class="btn remove"><i class="fas fa-trash remove">remove</i></button>
注意:因为你有button
和type='button'
,所以没必要用e.preventDefault()