如何删除事件监听器? [英] How to remove event listener?
本文介绍了如何删除事件监听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我的事件监听器代码
Below is my code for event listener
window.addEventListener("beforeunload", function (e) {
if(sessionStorage.token != "abide" ) {
// call api
}
});
如果我想删除此事件监听器该怎么办?
What if I want to remove this event listener, what should I do?
代码是否正常工作?
window.removeEventListener("before unload");
推荐答案
删除事件监听器 ,您的事件处理函数必须是外部命名函数,而不是匿名(您需要对该函数的引用):
To remove event listener, your event handler function has to be an external named function, not anonymous (you need a reference to that function):
window.addEventListener("beforeunload", functionToRun);
function functionToRun(e){
if(sessionStorage.token != "abide" ){
// call api
}
}
window.removeEventListener("beforeunload",functionToRun);
替代方案:您也可以将其删除使用 参数进行匿名函数调用。 callee ,它引用了匿名函数。
ex:
Alternative : You can also remove it inside the anonymous function call using arguments.callee which is referencing that anonymous function.
ex:
var button=document.getElementById('button');
button.addEventListener('click',function(e){
//some code to be runned
this.removeEventListener('click', arguments.callee);
});
注意:您的事件处理函数必须按顺序触发一次以上述方式删除它。
Note: your event handler function has to be fired once, in order to remove it in the above way.
var button = document.getElementById('button');
button.addEventListener('click', function(e) {
alert('clicked');
this.removeEventListener('click', arguments.callee);
});
<button id="button">click</button>
这篇关于如何删除事件监听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文