not selector, on() click event

后端 未结 2 1346
孤街浪徒
孤街浪徒 2021-02-20 07:35

I am having some problems in executing the following code:

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


        
2条回答
  •  面向向阳花
    2021-02-20 07:49

    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++);   
    });
    

    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++);   
    });
    

    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++);
    });
    

提交回复
热议问题