下面是我的事件监听器代码
window.addEventListener("beforeunload", function (e) {
if(sessionStorage.token != "abide" ) {
// call api
}
});如果我想删除这个事件监听器,我应该怎么做?
代码是否像下面这样工作??
window.removeEventListener("before unload");发布于 2016-04-26 21:47:03
要删除事件侦听器,事件处理函数必须是外部命名函数,而不是匿名函数(您需要对该函数的引用):
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>
https://stackoverflow.com/questions/36866715
复制相似问题