不是选择器,on()单击事件 [英] not selector, on() click event

查看:67
本文介绍了不是选择器,on()单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在执行以下代码时遇到一些问题:

I am having some problems in executing the following code:

    var i = 1;  
$('.hello:not(.selected)').on('click',function(){
    $(this).addClass('selected');       
    console.log(i++);   
});

问题是,添加所选类后,此代码仅应触发一次,但是它执行了很多次,我只希望 i 变量不增加.换句话说,我正在尝试执行以下操作(该方法有效,但由于已过时,所以我不想使用live函数):

The problem is that this code should trigger just ONE time after the class selected has added, but it is executing many times, I just want the i variable not to increase. In other words, I am trying to do the following (which works, but i don't want to use the live function since it has deprecated):

$('.hello:not(.selected)').live('click', function () { 
   $('.hello').removeClass('selected');
   $(this).addClass('selected');
... 
});

非常感谢您的提前回复, k

Thanks so much for your responses in advance, k

推荐答案

您的代码采用的是当前 满足以下条件的元素集:

Your code is taking the set of elements that currently satisfy this criteria:

$('.hello:not(.selected)')

并为所有永恒设置此事件处理程序 :

and setting up this event handler for all eternity:

.on('click',function(){
    $(this).addClass('selected');
    $(this).css({opacity : 0.5});       
    console.log(i++);   
});

特别重要的事实是,一旦在元素上设置了处理程序,即使该元素后来不再满足条件,它仍将继续处于活动状态(在这种情况下,通过获取selected类).

Particularly important is the fact that once the handler is set on an element, it will continue to be active even if later on that element no longer satisfies the criteria (in this case, by gaining the selected class).

有几种方法可以实现所需的行为.一种方法是动态检查事件处理程序中是否仍然保留过滤器"条件:

There are several ways to achieve the desired behavior. One would be to dynamically check that the "filter" condition still holds inside the event handler:

$('.hello').on('click',function(){
    if($(this).hasClass('selected')) {
        return;
    }
    $(this).addClass('selected');
    $(this).css({opacity : 0.5});       
    console.log(i++);   
});

另一种方法是委派该事件-在这种情况下,将在其后代之一中通知该事件的父元素,并会动态动态检查该后代是否满足过滤条件决定触发事件处理程序(从Ben Lee的答案中无耻地粘贴了代码):

Another would be to delegate the event -- in this case, a parent element would be notified of the event on one of its descendants and it would dynamically check that said descendant satisfies the filter condition before deciding to trigger the event handler (code shamelessly pasted from Ben Lee's answer):

$('body').on('click', '.hello:not(.selected)', function() {
    $(this).addClass('selected');
    $(this).css({opacity : 0.5});       
    console.log(i++);
});

这篇关于不是选择器,on()单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆