简体   繁体   English

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

[英]jQuery fires twice for two nested elements with the same class name

I have this button.我有这个按钮。 I just noticed, if I have the same class name on two nested elements, the click listener will fire twice.我刚刚注意到,如果我在两个嵌套元素上具有相同的 class 名称,则click侦听器将触发两次。 When I click, how can I fix this?当我点击时,我该如何解决这个问题?

 $('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>

You need to prevent propagation because you have parent/child with same class, so use e.stopPropagation()您需要防止传播,因为您的父/子具有相同的 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>


And here is JS pure solution这是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>

Note: because you have button with a type='button' , there is no need to use e.preventDefault()注意:因为你有一个type='button' button所以不需要使用e.preventDefault()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM