jQuery为具有相同类名的两个嵌套元素触发两次

杰姆兹

我有这个按钮。我只是注意到,如果在两个嵌套元素上具有相同的类名,则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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

区分具有相同类的两个html元素

如何区分具有相同类名的两个元素

Internet Explorer 8无法为具有相同类的两个元素加载CSS的问题

两个具有相同类名的jquery滑块,但是问题出在移动滑块上

检查具有相同类的两个元素的两个 ID 是否相等

给具有相同类的两个元素一个唯一的 id

隐藏具有相同类名的两个或多个列表中的项目

如何抓取具有相同类名的两个表?

使用jQuery在两个具有相同类的div之间检索HTML数据

两个具有相同类的Jquery Datatables无法正常工作

选择所有具有相同类的元素,有些元素有两个类

查找在Python中具有完全相同值的两个嵌套元素的列表元素

使用具有两个相同类的两个 div 的 Javascript

如何检查嵌套列表的两个元素在 Prolog 中是否具有相同的索引?

在jQuery Select元素中具有冗余或具有两个相同的类

两个具有相同变量名的foreach循环打破了元素的顺序

克隆两次jQuery按钮,让他们两个都完成相同的任务

量角器将两个具有相同类名的范围连接在一起

为具有两个相同类型类的自定义数据类型实现应用函子

使两个向量具有相同数量的元素

强制两个<li>元素具有相同的高度

如何平均两个具有相同元素的数组?

具有随机值的两个不同类具有相同的输出

具有嵌套ListView双击事件的ListView触发两次

React和React Router,使用不同的道具两次渲染同一元素会导致两个具有相同道具的元素?

简化LINQ-具有两个不同where子句的Col的和两次

2 具有相同类名的 css 文件,并且具有该类名的元素具有两种样式

为具有相同类的每个元素触发JS代码

具有相同数量的离散属性的两个相同类型的文件是否具有相同的大小?