如何在纯 JavaScript 中仅绑定一次事件监听器?

Pat*_*ack 7 javascript events

我已经知道 Jquery 解决方案

$('#myid').one('click', function(event) {
  ...
});
Run Code Online (Sandbox Code Playgroud)

但现在我正在寻找纯 JavaScript 方式,因为我没有使用 Jquery

我已经检查了一次选项,但并非所有浏览器都支持它,请参阅文档

小智 10

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

您可以传递第三个参数,一个选项对象,{ once: true }

在底部,您会注意到它不适用于 IE :(

const myElement = document.getElementById('my-element-id');

myElement.addEventListener('click', function namedListener() {
  // Remove the listener from the element the first time the listener is run:
  myElement.removeEventListener('click', namedListener);

  // ...do the rest of your stuff
});
Run Code Online (Sandbox Code Playgroud)