rof*_*rol 39
使用once,如果你不需要支持Internet Explorer:
element.addEventListener(event, func, { once: true });
Run Code Online (Sandbox Code Playgroud)
否则使用这个:
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!");
});
Run Code Online (Sandbox Code Playgroud)
SLa*_*aks 18
您可以使用jQuery的one方法,该方法仅订阅第一次出现的事件.
例如:
$('something').one('click', function(e) {
alert('You will only see this once.');
});
Run Code Online (Sandbox Code Playgroud)
只需在 addEventListener 方法调用中使用正确的选项:
element.addEventListener(event, func, { once: true })
Run Code Online (Sandbox Code Playgroud)
与 rofrol 的回答相同,只是另一种形式:
function addEventListenerOnce(element, event, fn) {
var func = function () {
element.removeEventListener(event, func);
fn();
};
element.addEventListener(event, func);
}
Run Code Online (Sandbox Code Playgroud)
rofrol 的 anwser 的稍微改进版本:
function addEventListenerOnce(target, type, listener) {
target.addEventListener(type, function fn() {
target.removeEventListener(type, fn);
listener.apply(this, arguments);
});
}
Run Code Online (Sandbox Code Playgroud)
通过使用 apply 传递所有参数this并按预期工作。