如何在纯JavaScript中仅将事件侦听器绑定一次? [英] How to bind an event listener only once in pure JavaScript?

查看:112
本文介绍了如何在纯JavaScript中仅将事件侦听器绑定一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道Jquery解决方案

I already know the Jquery solution

$('#myid').one('click', function(event) {
  ...
});

但是现在我找到了纯JavaScript方式,因为我没有使用Jquery

But now I'm finding the Pure JavaScript way because I'm not using Jquery

我已经选中了一次选项,但是并非所有浏览器都支持它,请参见

I have checked the once option but it is not supported by all browsers see the docs

推荐答案

您可以使用{ once: true }

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

At the bottom, you'll notice it doesn't work for 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
});

这篇关于如何在纯JavaScript中仅将事件侦听器绑定一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆