我想删除使用addEventListener()添加的所有特定类型的事件侦听器。我所看到的所有资源都在告诉你需要这样做:
elem.addEventListener('mousedown',specific_function);
elem.removeEventListener('mousedown',specific_function);
但我希望能够在不知道它目前是什么情况下清除它,就像这样:
elem.addEventListener('mousedown',specific_function);
elem.removeEventListener('mousedown');
你也可以重写'yourElement.addEventListener()'方法,并使用'.apply()'方法像正常一样执行侦听器,但在进程中拦截函数。如:
<script type="text/javascript">
var args = [];
var orginalAddEvent = yourElement.addEventListener;
yourElement.addEventListener = function() {
//console.log(arguments);
args[args.length] = arguments[0];
args[args.length] = arguments[1];
orginalAddEvent.apply(this, arguments);
};
function removeListeners() {
for(var n=0;n<args.length;n+=2) {
yourElement.removeEventListener(args[n], args[n+1]);
}
}
removeListeners();
</script>
此脚本必须在页面加载时运行,否则可能无法拦截所有事件侦听器。
确保在使用之前删除' removelistener()'调用。
在不引用原始函数的情况下删除事件侦听器的现代方法是使用AbortController。需要注意的是,您只能中止您自己添加的侦听器。
const buttonOne = document.querySelector('#button-one');
const buttonTwo = document.querySelector('#button-two');
const abortController = new AbortController();
// Add multiple click event listeners to button one
buttonOne.addEventListener(
'click',
() => alert('First'),
{ signal: abortController.signal }
);
buttonOne.addEventListener(
'click',
() => alert('Second'),
{ signal: abortController.signal }
);
// Add listener to remove first button's listeners
buttonTwo.addEventListener(
'click',
() => abortController.abort()
);
<p>The first button will fire two alert dialogs when clicked. Click the second button to remove those listeners from the first button.</p>
<button type="button" id="button-one">Click for alerts</button>
<button type="button" id="button-two">Remove listeners</button>