can't remove specific event handlers when attached to document with .on()

巧了我就是萌 提交于 2019-12-12 11:21:17

问题


Here's a simple fiddle to demo my situation...

http://jsfiddle.net/UnsungHero97/EM6mR/17/

What I'm doing is adding an event handler for current & future elements, using .on(). I want to be able to remove these event handlers for specific elements when something happens; in the case of the fiddle, when the radio button is selected, the event handler for the blue elements should be removed and clicking those elements should not do anything anymore.

It doesn't seem to be working :(

How do I remove the event handler attached to document that I created with .on() for those specific blue elements?


回答1:


The signature for your .on() and .off() has to match.

These two do not match so the .off() call won't find matching event handlers to remove:

$(document).on('click', '.btn', function() {
    update();
});

$(document).off('click', '.blue');

Note, the selector passed to .on() and .off() is different.


When using the dynamic form of .on() (where you pass a selector as an argument to .on()), you can't remove just part of the items. That's because there's only one event handler installed on the root element and jQuery can only remove the entire thing or not at all. So, you can't just .off() some of the dynamic items.

Your options are to remove all the event handlers with:

$(document).off('click', '.btn');

and, then install a new event handler that excludes the items you don't want such as:

$(document).off('click', '.btn:not(.blue)');

Or, teach the event handler itself how to ignore .blue items:

$(document).on('click', '.btn', function() {
    if (!$(this).hasClass('blue')) {
        update();
    }
});



回答2:


Be careful of how you attach your events; this works fine for me:

$('.btn').on('click', function() {
    update();
});

$('#disable').on('change', function() {
        $('.btn').off('click');
});



回答3:


Only way seems to be:

$('#disable').on('change', function() {

        $(document)
           .off('click', '.btn')
           .on('click', '.btn:not(.blue)', update);
    });


来源:https://stackoverflow.com/questions/15887675/cant-remove-specific-event-handlers-when-attached-to-document-with-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!