30秒学会 JavaScript 片段 · 2017年9月13日

30秒学会 JavaScript 片段 – off

Removes an event listener from an element.

Use EventTarget.removeEventListener() to remove an event listener from an element.
Omit the fourth argument opts to use false or specify it based on the options used when the event listener was added.

代码片段

const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);

使用样例

const fn = () => console.log('!');
document.body.addEventListener('click', fn);
off(document.body, 'click', fn); // no longer logs '!' upon clicking on the page