我在使用jQuery .off()删除jQuery事件侦听器时遇到麻烦,该附件已附加到带有event.data的按钮上。这是我为执行所需操作而开发的代码:

function test1(){
    //some data to be used on click at button 'lets go'
    var i=1;
    function test2(event){
        event.data.i++;
        console.log("i="+event.data.i);
        console.log("i_original="+i);
    }

    $('#letsGo').off('click'); //cannot use, as it is required in global scope with different handler function
    $('#letsGo').off('click', test2); //not working
    $('#letsGo').off('click', {'i':i}, test2); //not working
    $('#letsGo').off('click', {'i':i}, test2(event)); //not working
    $('#letsGo').off('click', test2(event)}; //not working

    //some code here
    $('#letsGo').on('click', {'i':i}, test2); //this is where it get's attached after removing existing handler
}
在以下操作序列中调用上述函数:
test1() //function call
    click @ letsGo
    click @ letsGo
    click @ letsGo
test1() //again function call to remove existing handlers and attach new one
    click @ letsGo
test1() //again function call
    click @ letsGo
    click @ letsGo
.....continues
上面的jQuery .off()方法的问题在于它没有删除现有事件,而是始终附加一个新事件。因此,无论何时进行函数调用,都将再有一个事件侦听器。这不是期望的行为。
我想要的此功能是.off()可以工作,即使有event.data属性也是如此。
因此,请帮助我。

最佳答案

首先,在附加事件时为事件命名空间:

$('#letsGo').on('click.test2', {'i':i}, test2);
然后,当您只想删除test2函数时,请以您先前创建的 namespace 作为目标:
 $('#letsGo').off('click.test2');

09-30 16:14
查看更多