简体   繁体   中英

jquery on() and off() dont work

first i register an event

$(document).on('change',"*[dependent-group]", function (e) {
        e.stopImmediatePropagation();
        debugger;
        if ($(this).val()) {
            obj.dependentLists($(this), $(this).val());
        } else {
            obj.resetLists($(this));
        }
    });

then i turn it off with

 $(document).off('change',"*[dependent-group]");

The problem is that i attach the event again, it doesnt fire.

Is $(document).on('change',"*[dependent-group]") how you "attach the event again"? If, yes, it doesn't reattach the first handler. You have to pass the handler.

function handler(e) {
    e.stopImmediatePropagation();
    debugger;
    if ($(this).val()) {
        obj.dependentLists($(this), $(this).val());
    } else {
        obj.resetLists($(this));
    }
}

$(document).on('change',"*[dependent-group]", handler); 
$(document).off('change',"*[dependent-group]", handler);
$(document).on('change',"*[dependent-group]", handler);

Note that you can also define a switch variable instead of using off and reattaching the handler.

var run = true;
function handler(e) {
    if (!run) return;
    e.stopImmediatePropagation();
    debugger;
    if ($(this).val()) {
        obj.dependentLists($(this), $(this).val());
    } else {
        obj.resetLists($(this));
    }
}

$(document).on('change',"*[dependent-group]", handler); 
// ...
run = false;
// ...
run = true;

To turn it on:

$(document).find("*[dependent-group]").change( function (e) {
        e.stopImmediatePropagation();
        debugger;
        if ($(this).val()) {
            obj.dependentLists($(this), $(this).val());
        } else {
            obj.resetLists($(this));
        }
    });

To turn it off:

$(document).find("*[dependent-group]").off('change')

if you want you can belt and braces:

$(document).find("*[dependent-group]").off('change').change( function (e) {
        e.stopImmediatePropagation();
        debugger;
        if ($(this).val()) {
            obj.dependentLists($(this), $(this).val());
        } else {
            obj.resetLists($(this));
        }
    });

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