javascript 如何添加一次单击功能的事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28610365/
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-10-28 09:15:56  来源:igfitidea点击:

How can I add an event for a one time click to a function?

javascript

提问by Adam Piper

I would like to add a click event listener to a function but would only like it to happen once. How could i do this?

我想向函数添加一个单击事件侦听器,但只希望它发生一次。我怎么能这样做?

I would like to stay clear of JQuery as well if it is possible please.

如果可能的话,我也想远离 JQuery。

EDITED

已编辑

As the answers that I am getting for this are fully satisfying my need i though i may make it a bit more clear with context.

由于我为此得到的答案完全满足了我的需要,但我可能会根据上下文使其更加清晰。

I am writing a function to draw a rectangle, first with one click on a button to initiate the rectangle function. Then there are two click event listeners in the drawRectangle function. These are the events i would like to happen only once in the function. Allowing the user to then create another rectangle if they click on the rectangle initiation button again.

我正在编写一个绘制矩形的函数,首先单击一个按钮来启动矩形函数。然后在 drawRectangle 函数中有两个点击事件监听器。这些是我希望在函数中只发生一次的事件。如果用户再次单击矩形启动按钮,则允许用户创建另一个矩形。

回答by Gibolt

Use modern JavaScript!

使用现代 JavaScript!

EventTarget.addEventListener("click", function() {

    // Do something cool

}, {once : true});

A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

- MDN web docs

一个布尔值,指示添加后最多应调用一次侦听器。如果true,则在调用时会自动删除侦听器。

- MDN 网络文档

Here's a list of browsersthat support this feature (94% as of Mar 2020)

这是支持此功能的浏览器列表(截至 2020 年 3 月为 94%)

Other reference

其他参考

回答by Florian Margaine

You have to use removeEventListeneronce the event is fired once. However, removeEventListenertakes a function as argument, which means you need to declare a named function, add it with addEventListener, and have it removing itself. Example:

removeEventListener一旦事件被触发一次,您必须使用一次。但是,removeEventListener将函数作为参数,这意味着您需要声明一个命名函数,将其添加为addEventListener,然后将其自身移除。例子:

function foo() {
    // do things, then
    removeEventListener('click', foo);
}

addEventListener('click', foo);

回答by jgillich

function one(el, type, fn) {
    function handler(event) {
        el.removeEventListener(type, handler);
        fn(event);
    }
    el.addEventListener(type, handler);
}

// use it like
one(window, 'resize', function () {
    alert("This triggers just once");
});

Example: http://jsfiddle.net/6njpem7x/

示例:http: //jsfiddle.net/6njpem7x/

回答by Felix Kling

The other answers are correct in that this can be achieved with a named function, but you don't need to declare the function separately. You can use a named function expression:

其他答案是正确的,因为这可以通过命名函数来实现,但您不需要单独声明该函数。您可以使用命名函数表达式

element.addEventListener("click", function handler(event) {
  this.removeEventListener("click", handler);
  // ...
});

An alternative, though less optimal, approach is to keep around a variable that keeps track whether the handler was executed:

另一种虽然不太理想的方法是保留一个变量来跟踪处理程序是否被执行:

var wasExecuted = false;
element.addEventListener("click", function(event) {
  if (wasExecuted) {
    return;
  }
  wasExecuted = true;
  // ...
});

The variable needs to be declared outside the handler but within scope, so that its value persists across event triggers.

该变量需要在处理程序之外但在范围内声明,以便其值在事件触发器之间保持不变。

回答by CodingIntrigue

Combination of addEventListenerand removeEventListener:

addEventListenerremoveEventListener 的组合:

element.addEventListener("click", clickFunction);
function clickFunction(e) {
    console.log("clicked");
    element.removeEventListener("click", clickFunction);
}

jsFiddle

js小提琴

回答by Joe Fitter

something like this

像这样的东西

var el = document.getElementById('something');
el.addEventListener('click', doSomething);

function doSomething() {
  el.removeEventListener('click', doSomething);

  //code
}

回答by n-dru

You can set a cookie after first click:

您可以在第一次点击后设置 cookie:

document.cookie="click=1; expires=.......";

and add condition to listener - if cookie is set, you omit that.

并将条件添加到侦听器 - 如果设置了 cookie,则忽略它。