首页 > 解决方案 > 即使我使用的是 :not 选择器,也会触发事件侦听器

问题描述

$('.user-card:not(.loaded)').click(function(e) {
  $(e.target).addClass('loaded');
  $(e.target).text('loaded!');
  console.log('this is now loaded');
});

$('.loaded').click(function() {
  alert('already loaded!')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="user-card">
  not loaded
</button>
<button type="button" class="user-card">
  not loaded
</button>

我不想要“加载!” 按钮来激活'.user-card:not(.loaded)' 事件侦听器,但它确实如此。为什么是这样?

标签: javascriptjquerycss

解决方案


click 事件每次都会触发,因为您没有在每次点击后重新分配点击事件。对于如何解决这个问题,您有多种选择。我在这里的一种方法是在单击时查看“已加载”类。如果它没有“加载”类,那么它运行代码。否则,警报会触发,让您知道元素已经加载。

$('.user-card:not(.loaded)').click(function(e) {
  if (!$(e.target).hasClass('loaded')) {
    $(e.target).addClass('loaded');
    $(e.target).text('loaded!');
    console.log('this is now loaded');
  } else {
    alert('already loaded!');
  }
});

$('.loaded').click(function() {
  alert('already loaded!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="user-card">
  not loaded
</button>
<button type="button" class="user-card">
  not loaded
</button>
<button type="button" class="user-card loaded">
  loaded
</button>


推荐阅读