强制 javascript EventListener 执行一次?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4878805/
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
force javascript EventListener to execute once?
提问by Skizit
I'm wondering is it possible for force a javascript event listener to, without the condition being true force it to execute once then continue listening for it's condition to be met to execute further?
我想知道是否有可能强制 javascript 事件侦听器在条件不为真的情况下强制执行一次然后继续侦听满足条件以进一步执行?
回答by Jlam
var clickFunction = function (event) {
//do some stuff here
window.removeEventListener('click',clickFunction, false );
};
window.addEventListener("click", clickFunction, false);
This will let you fire the clickFunction once, as the magic of closure let the removeEventListener find the clickFunction.
这将让您触发 clickFunction 一次,因为闭包的魔力让 removeEventListener 找到 clickFunction。
No need to use a library just to get something simple done.
无需使用库来完成一些简单的事情。
回答by Crayon Violent
if you wrap the code in a function, just call the function on page load
如果您将代码包装在一个函数中,只需在页面加载时调用该函数
edited to add example:
编辑添加示例:
dunno what your event is but here's an example:
不知道你的活动是什么,但这里有一个例子:
<a ..onclick='someFunction()'>click</a>
<script type='text/javascript'>
function someFunction() {
// do whatever
}
// call the function
someFunction();
</script>
回答by KOGI
If I understand your question correctly, you only want to handle one event at a time (if an event fires multiple times in rapid succession, you only want to handle one of them) then once the handler is complete, you will continue to listen for more events. Correct?
如果我正确理解您的问题,您一次只想处理一个事件(如果一个事件快速连续多次触发,您只想处理其中一个),那么一旦处理程序完成,您将继续监听更多活动。正确的?
jQuery has a .one( ) method api.jquery.com/one
jQuery 有一个 .one() 方法 api.jquery.com/one
It only handles the event once, but if you re-bind the event in the handler, then it will function as you want.
它只处理一次事件,但如果您在处理程序中重新绑定该事件,那么它将按您的需要运行。
function handler( )
{
// do stuff
$(this).one( 'click', handler );
}
$('.someElement').one( 'click', handler );