[英]Event listener is triggered even though I'm using :not selector
$('.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>
I don't want the "loaded!"我不想要“加载!” button to acctivate the
'.user-card:not(.loaded)'
event listener, yet it does.按钮激活
'.user-card:not(.loaded)'
事件侦听器,但它确实如此。 Why is this?为什么是这样?
The click event will fire every time because you aren't reassigning click events after each click.每次点击后都会触发点击事件,因为您不会在每次点击后重新分配点击事件。 You have multiple choices on how to address this.
关于如何解决这个问题,您有多种选择。 One way I have here is to look at the "loaded" class on the click.
我在这里的一种方法是在单击时查看“加载”类。 If it does not have the class "loaded" then it runs the code.
如果它没有“加载”类,则它运行代码。 Otherwise the alert fires to let you know the element has already been loaded.
否则警报会触发,让您知道元素已经加载。
$('.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>
通过从父级继承属性,两个按钮都“未加载”,请改用“.hasClass”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.