以下是我的事件监听器代码:
window.addEventListener("beforeunload", function (e) {
if(sessionStorage.token != "abide" ) {
// call api
}
});
如果我想删除这个事件监听器,我该怎么做?
代码是否像下面这样工作?
window.removeEventListener("before unload");
以下是我的事件监听器代码:
window.addEventListener("beforeunload", function (e) {
if(sessionStorage.token != "abide" ) {
// call api
}
});
如果我想删除这个事件监听器,我该怎么做?
代码是否像下面这样工作?
window.removeEventListener("before unload");
为了移除事件监听器,你的事件处理函数必须是一个外部命名函数,而不是匿名函数(你需要对该函数有一个引用):
window.addEventListener("beforeunload", functionToRun);
function functionToRun(e){
if(sessionStorage.token != "abide" ){
// call api
}
}
window.removeEventListener("beforeunload",functionToRun);
var button=document.getElementById('button');
button.addEventListener('click',function(e){
//some code to be runned
this.removeEventListener('click', arguments.callee);
});
注意: 你的事件处理函数必须被触发一次,才能以上述方式移除它。
var button = document.getElementById('button');
button.addEventListener('click', function(e) {
alert('clicked');
this.removeEventListener('click', arguments.callee);
});
<button id="button">click</button>
arguments.callee
不起作用。最好给该函数命名。 - Felix Kling