我的addEventListener(#btn-1)中有一个函数,我想最终删除它.我知道将函数保存到变量是一种方法,但除非将其包装在函数中,否则传递"this"将不起作用,而函数现在无法删除,因为它要么是匿名函数,要么不是对同一函数的引用,即使它已命名.有没有办法做到这一点?
const anonFunction = function(dis, str) {
console.log(dis);
console.log(str);
}
const myFn = function() {
anonFunction(this, 'hello world');
}
document.querySelector('#btn-1').addEventListener('click', function() {
anonFunction(this, 'hello world');
});
document.querySelector('#btn-2').addEventListener('click', function() {
// doesn't work
document.querySelector('#btn-1').removeEventListener('click', anonFunction);
});
<button id="btn-1" type="button">Call Function</button>
<button id="btn-2" type="button">Remove Event Listener</button>
UPDATE: SOLVED
使另一个函数调用分配给变量的主函数,并在添加和删除事件侦听器时将其作为要插入的函数.
const anonFunction = function(dis, str) {
console.log(dis);
console.log(str);
}
const myFn = function() {
anonFunction(this, 'hello world');
}
document.querySelector('#btn-1').addEventListener('click', myFn);
document.querySelector('#btn-2').addEventListener('click', function() {
document.querySelector('#btn-1').removeEventListener('click', myFn);
});
<button id="btn-1" type="button">Call Function</button>
<button id="btn-2" type="button">Remove Event Listener</button>