简体   繁体   中英

jquery .off doesn't seem to work

so I'll be short: jquery .off() doesn't disable a listen I've set with .on .

html:

<span id="myspan">lol</span>
<button id="b1">jquery On</button>
<button id="b2">jquery Off</button>

js:

$("#b1").on("click", add);
$("#b2").on("click", del);

function add() {
    $("#myspan").on("click", function(e) {
        var a = 1;
        testfunc(a, e);
    });
}

function del() {
    $("#myspan").off("click", testfunc);
}

function testfunc(num, event) {
   alert(num);
}

So first we add to myspan the testfunc() by clicking the jquery On button. After we do that, if we click on the span, we get an alert. Next, we click the jquery off button. That is supposed to remove the listener but it doesn't. Even after that, when we click on myspan testfunc is still attached.

Why? And how can I remove it ?

Your parameters don't match

It doesn't because you bound to a different function (anonymous one). And then you're trying to unbind from testfunc ... In order for your event (un)binding to work both parameters between on and off must match .

Possible workaround

If this is the only click event listener on the element, then it's be easiest way to unbind from your anonymous function by calling:

$("#myspan").off("click");

If you're binding several event handlers to click event on the same element then you can also distinguish them by providing namespaces and then use proper namespacing in off call.

$("#myspan").on("click.test", function(e) { ... });
...
$("#myspan").off("click.test");

Or use just namespace if you'd like to unbind several different event handlers that were bound using the same namespace:

$("#myspan").off(".test");

You're not binding the event handler to testfunc , you're binding it to an anonymous function, and whitin that function you're just calling testfunc , so you can't automatically unbind that.

It's either

$("#myspan").on("click", testfunc); // bind function

and then

$("#myspan").off("click", testfunc); // unbind function

or to unbind the anonymous function, just

$("#myspan").off("click"); // remove all handlers

or you can also namespace the handler

$("#myspan").on("click.test", function(e) {
    var a = 1;
    testfunc(a, e);
});

and to remove only that handler

$("#myspan").off("click.test");

In this simple case, replace your off call with this:

function del() {
    $("#myspan").off("click");
}

You don't need to pass the handler function to the off call, and if you do, it will only remove that particular handler. However, you did not attach testfunc , but an anonymous function that just calls testfunc() . Therefore, your off call does nothing.

Also, you never assigned the variable testfunc .

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