30秒学会 JavaScript 片段 · 2023年1月13日

30秒学会 JavaScript 片段 – Remove event listeners from target

Detaches an event listener from all the provided targets.

  • Use Array.prototype.forEach() and EventTarget.removeEventListener() to detach the provided listener for the given event type from all targets.

代码实现

const removeEventListenerAll = (
  targets,
  type,
  listener,
  options,
  useCapture
) => {
  targets.forEach(target =>
    target.removeEventListener(type, listener, options, useCapture)
  );
};

const linkListener = () => console.log('Clicked a link');
document.querySelector('a').addEventListener('click', linkListener);
removeEventListenerAll(document.querySelectorAll('a'), 'click', linkListener);

翻译自:https://www.30secondsofcode.org/js/s/remove-multiple-event-listeners