There is a simple code:

$('.like').on("click", function(){ console.log("click_l"); $(this).addClass('unlike'); }); $('.unlike').on("click",function(){ console.log("click_u"); $(this).addClass('like'); }); <button class="btn btn-default card_body_like like_div unlike"><div></div></button> 

As you can see, the unlike class initially (it has its own style, lights, like in like). The problem is that it constantly displays click_u in the console, that is, even when the unlike class has disappeared, and instead of it, put like - it accepts this button as an element with class unlike

    1 answer 1

    Because $('.like').on("click" ... runs once and attaches a click handler to the $('.like') selection elements, that is, elements with the "like" class at the time this code is executed.

     $('.container').on("click", '.like,.unlike', function() { if ($(this).hasClass('like')) console.log("click_l"); if ($(this).hasClass('unlike')) console.log("click_u"); $(this).toggleClass('unlike like'); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <button class="btn btn-default card_body_like like_div unlike"><div>Click</div></button> </div> 

    • Well, ok, as an option. But what is the reason that I did not work out? why does not it work? - shumik_UA
    • @shumik_UA Did you read three lines at the beginning of the answer? Is there something incomprehensible in them? - Igor
    • I see, I did not update it - shumik_UA