Event Response Questions

I can’t understand why Testcontinue to shoot, although a class has openbeen added to it? any idea on how to do this correctly so that it stops firing when adding an open class?

<div class="changer">Test</div>
$(".changer:not('open')").on("click",function(){
        $(this).addClass("open");
        alert("passed");
    })

http://jsfiddle.net/ng2guchg/

+4
source share
1 answer

This is because the elements receive when the page loads, and the event handler is connected at that moment, changing the class later does not remove the event handler.

The solution is to either check the class inside the event handler

$(".changer").on("click", function(){
    if ( ! $(this).hasClass('open') ) {
        $(this).addClass("open");
        alert("passed");
    }
});

, jQuery one(), .

+5

Source: https://habr.com/ru/post/1568986/


All Articles