如何为一次性单击功能添加事件? [英] How can I add an event for a one time click to a function?

查看:67
本文介绍了如何为一次性单击功能添加事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在函数中添加一个click事件监听器,但只希望它发生一次。我怎么能这样做?

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?

如果有可能的话,我也想清楚JQuery。

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

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.

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

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.

推荐答案

您必须使用<$ c一旦事件被触发一次,$ c> removeEventListener 。但是, removeEventListener 将一个函数作为参数,这意味着你需要声明一个命名函数,用 addEventListener 添加它,让它自己去除。示例:

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

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

addEventListener('click', foo);

这篇关于如何为一次性单击功能添加事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆