jquery .off似乎不起作用 [英] jquery .off doesn't seem to work

查看:583
本文介绍了jquery .off似乎不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我会做空:jquery .off()不会禁用我用 .on

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);
}

首先我们添加 myspan testfunc()单击 jquery On 按钮。在我们这样做之后,如果我们点击跨度,我们会收到警报。接下来,我们单击 jquery off 按钮。这应该是删除监听器,但它没有。即便如此,当我们点击 myspan testfunc 仍然附加。

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 ?

推荐答案

您的参数不匹配



它不是因为你绑定了一个不同的功能(匿名的)。然后你试图解开 testfunc ...为了让你的事件(un)绑定工作 之间的两个参数 off 必须匹配

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.

如果这是元素上唯一的单击事件监听器,那么通过调用以下方法解除匿名函数取消是最简单的方法:

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");

如果您将多个事件处理程序绑定到同一元素上的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");

这篇关于jquery .off似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆