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

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

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

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

当前回答

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

document.body.innerHTML = document.body.innerHTML

其他回答

 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)
}

你也可以重写'yourElement.addEventListener()'方法,并使用'.apply()'方法像正常一样执行侦听器,但在进程中拦截函数。如:

<script type="text/javascript">

    var args = [];
    var orginalAddEvent = yourElement.addEventListener;

    yourElement.addEventListener = function() {
        //console.log(arguments);
        args[args.length] = arguments[0];
        args[args.length] = arguments[1];
        orginalAddEvent.apply(this, arguments);
    };

    function removeListeners() {
        for(var n=0;n<args.length;n+=2) {
            yourElement.removeEventListener(args[n], args[n+1]);
        }
    }

    removeListeners();

</script>

此脚本必须在页面加载时运行,否则可能无法拦截所有事件侦听器。

确保在使用之前删除' removelistener()'调用。

在不引用原始函数的情况下删除事件侦听器的现代方法是使用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>

我知道这是旧的,但我有一个类似的问题,没有真正的答案,我想从文档中删除所有按键事件侦听器。我没有删除它们,而是重写addEventListener,在添加它们之前忽略它们,类似于tom上面的回答,在加载任何其他脚本之前添加这个:

<script type="text/javascript">
    var current = document.addEventListener;
    document.addEventListener = function (type, listener) {
        if(type =="keydown")
        {
            //do nothing
        }
        else
        {
            var args = [];
            args[0] = type;
            args[1] = listener;
            current.apply(this, args);
        }
    };
</script>

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

document.body.innerHTML = document.body.innerHTML