我想删除使用addEventListener()添加的所有特定类型的事件侦听器。我所看到的所有资源都在告诉你需要这样做:

elem.addEventListener('mousedown',specific_function);
elem.removeEventListener('mousedown',specific_function);

但我希望能够在不知道它目前是什么情况下清除它,就像这样:

elem.addEventListener('mousedown',specific_function);
elem.removeEventListener('mousedown');

当前回答

在不引用原始函数的情况下删除事件侦听器的现代方法是使用AbortController。需要注意的是,您只能中止您自己添加的侦听器。

const buttonOne = document.querySelector('#button-one'); const buttonTwo = document.querySelector('#button-two'); const abortController = new AbortController(); // Add multiple click event listeners to button one buttonOne.addEventListener( 'click', () => alert('First'), { signal: abortController.signal } ); buttonOne.addEventListener( 'click', () => alert('Second'), { signal: abortController.signal } ); // Add listener to remove first button's listeners buttonTwo.addEventListener( 'click', () => abortController.abort() ); <p>The first button will fire two alert dialogs when clicked. Click the second button to remove those listeners from the first button.</p> <button type="button" id="button-one">Click for alerts</button> <button type="button" id="button-two">Remove listeners</button>

其他回答

 var events = [event_1, event_2,event_3]  // your events

//make a for loop of your events and remove them all in a single instance

 for (let i in events){
    canvas_1.removeEventListener("mousedown", events[i], false)
}

如果不拦截addEventListener调用并跟踪侦听器,或者使用允许这些功能的库,这是不可能的。如果监听器集合是可访问的,但没有实现该特性,则会出现这种情况。

您可以做的最接近的事情是通过克隆元素来删除所有侦听器,这将不会克隆侦听器集合。

注意:这也会删除element子元素上的监听器。

var el = document.getElementById('el-id'),
    elClone = el.cloneNode(true);

el.parentNode.replaceChild(elClone, el);

在不引用原始函数的情况下删除事件侦听器的现代方法是使用AbortController。需要注意的是,您只能中止您自己添加的侦听器。

const buttonOne = document.querySelector('#button-one'); const buttonTwo = document.querySelector('#button-two'); const abortController = new AbortController(); // Add multiple click event listeners to button one buttonOne.addEventListener( 'click', () => alert('First'), { signal: abortController.signal } ); buttonOne.addEventListener( 'click', () => alert('Second'), { signal: abortController.signal } ); // Add listener to remove first button's listeners buttonTwo.addEventListener( 'click', () => abortController.abort() ); <p>The first button will fire two alert dialogs when clicked. Click the second button to remove those listeners from the first button.</p> <button type="button" id="button-one">Click for alerts</button> <button type="button" id="button-two">Remove listeners</button>

你不能删除一个事件,但是全部?在一次?只做

document.body.innerHTML = document.body.innerHTML

因此,这个函数将删除元素上的大部分指定侦听器类型:

function removeListenersFromElement(element, listenerType){
  const listeners = getEventListeners(element)[listenerType];
  let l = listeners.length;
  for(let i = l-1; i >=0; i--){
    removeEventListener(listenerType, listeners[i].listener);
  }
 }

有一些罕见的例外,其中一个不能删除的原因。