Javascript 只触发一次事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3393686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:26:40  来源:igfitidea点击:

Only fire an event once?

javascriptjqueryjavascript-events

提问by Qcom

How do I control only firing an event once?

如何控制只触发一次事件?

Actually, a quick google appears to allude to the fact that .one helps..

实际上,一个快速的谷歌似乎暗示了一个事实,即 .one 有帮助......

采纳答案by SLaks

You can use jQuery's onemethod, which will subscribe to only the first occurrence of an event.
For example:

您可以使用 jQuery 的one方法,该方法将仅订阅第一次发生的事件。
例如:

$('something').one('click', function(e) {
    alert('You will only see this once.');
});

回答by rofrol

Use onceif you don't need to support Internet Explorer:

使用once,如果你不需要支持Internet Explorer:

element.addEventListener(event, func, { once: true });

Otherwise use this:

否则使用这个:

function addEventListenerOnce(target, type, listener, addOptions, removeOptions) {
    target.addEventListener(type, function fn(event) {
        target.removeEventListener(type, fn, removeOptions);
        listener.apply(this, arguments);
    }, addOptions);
}

addEventListenerOnce(document.getElementById("myelement"), "click", function (event) {
    alert("You'll only see this once!");
});

回答by ling

Same as rofrol's answer, just another form:

与 rofrol 的回答相同,只是另一种形式:

    function addEventListenerOnce(element, event, fn) {
        var func = function () {
            element.removeEventListener(event, func);
            fn();
        };
        element.addEventListener(event, func);
    }

回答by Shikyo

Slightly improved version of rofrol's anwser:

rofrol 的 anwser 的稍微改进版本:

function addEventListenerOnce(target, type, listener) {
    target.addEventListener(type, function fn() {
        target.removeEventListener(type, fn);
        listener.apply(this, arguments);
    });
}

By using apply all arguments are passed and the thisworks as expected.

通过使用 apply 传递所有参数this并按预期工作。

回答by kapitalny

Just use proper option in your addEventListener method call:

只需在 addEventListener 方法调用中使用适当的选项:

element.addEventListener(event, func, { once: true })

回答by John Weisz

Additionally, you can do this:

此外,您可以这样做:

window.addEventListener("click", function handleClick(e) {
    window.removeEventListener("click", handleClick);

    // ...
});

回答by kofifus

Added the options for add/remove event listener:

添加了添加/删除事件侦听器的选项:

function addEventListenerOnce(target, type, listener, optionsOrUseCaptureForAdd, optionsOrUseCaptureForRemove) {
    const f = event => {
        target.removeEventListener(type, f, optionsOrUseCaptureForRemove);
        listener(event);
    }
    target.addEventListener(type, f, optionsOrUseCaptureForAdd);
}