如何在纯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
答
在底部,您会注意到它不适用于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
});