简体   繁体   中英

Jquery - Still active after removing class from element

I don't know if it's supposed to be like this, and I am doing something fundamentally wrong.

I have a div with a given class and when you click on the div it gives a response, but then I have another div and when clicking on that one it removes the class from the first div .

However when I continue clicking on the first div after removing its class, I continue to get a response.

Why do the clicks continue to respond after I've removed the class?

HTML

<div class="testing">Testing</div>

<div id="testing_remover">Remove class from testing</div>

JS:

$(document).ready(function(){
    $('.testing').click(function(){
        console.log('testing is active');
    });

    $('#testing_remover').click(function(){
        $('.testing').removeClass('testing');
    });
});

Fiddle: http://jsfiddle.net/P3NpK/

Event handlers are bound to the element, not the selector.

To remove a handler, use .off() :

$(".testing").off("click");

Versions of jQuery earlier than 1.7 should preferably use .unbind instead of .off .

You'll have to either delegate the event handler higher up the DOM tree, or explicitly unbind the event handler. Once the event is bound to an element, just changing the class name won't remove event handlers.

To remove the event handler ( updated fiddle ):

$('#testing_remover').click(function(){
    $('.testing').off('click');
});

To delegate the event handler ( updated fiddle ):

$(document).on("click", ".testing", function(){
    console.log('testing is active');
});

The reason the delegation approach works is that jQuery captures the event once it's bubbled to the selected element (in this case, the document ). It checks to see if the event target matches the selector, and if so, executes the event handler. If you've removed the class, the target will no longer match the selector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM