javascript - 即使我使用的是 :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)'
事件侦听器,但它确实如此。为什么是这样?
解决方案
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>
推荐阅读
- java - recursive JSON java
- html - 如何重置 ng-multiselect-dropdown
- scala - Extract SparkSession from SparkContext
- css - 使用 NPM node-sass 观看 SASS 文件
- c - Should I redeclare a part of an external array for the use in a module
- android - Is it possible to make a wear app that connects to my android app activity(maps)
- mysql - 选择所有数据库中列的总和
- php - 如何在教义中使用左子句?
- azure - Azure 流分析的嵌套条件
- angular - Firebase 部署后显示“找不到页面”错误