【问题标题】:jQuery fires twice for two nested elements with the same class namejQuery 为具有相同类名的两个嵌套元素触发两次
【发布时间】: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


【解决方案1】:

你需要防止传播,因为你有同一个类的父/子,所以使用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 =&gt; 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>

注意:因为你有buttontype='button',所以不需要使用e.preventDefault()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多