如何解决无法删除Javascript
我在使用jQuery .off()
删除jQuery事件侦听器时遇到麻烦,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(event)); //not working
$('#letsGo').off('click',test2(event)}; //not working
//some code here
$('#letsGo').on('click',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
以上功能按以下操作顺序调用:
.off()
上述jQuery .off()
方法的问题在于它没有删除现有事件,而是始终附加一个新事件。因此,无论何时进行函数调用,都将再有一个事件侦听器。这不是期望的行为。
即使有event.data
属性,我想要的所有功能都是string1 = " {
"id": "101","created_time": 1603302391,"created_user_id": "58749658","created_user": "siva",},{
"id": "102","created_time": 1603302394,"created_user_id": "32145678",}"
string2 = " {
"id": "111","created_time": 1603382391,"created_user_id": "7894569","notes":"segrsegeg"
},"notes":"segrsegeg"
}"
。
所以,请帮助我。
解决方法
首先,在附加事件时命名空间:
$('#letsGo').on('click.test2',{'i':i},test2);
然后,当您只想删除test2函数时,请以您先前创建的名称空间作为目标:
$('#letsGo').off('click.test2');
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。