[英]How can I break or return from addeventlistener
I don't know how to break or return from addEventListener我不知道如何中断或从 addEventListener 返回
Here I get "Undefined label 'testfunc'" error在这里我得到“未定义的 label 'testfunc'”错误
testfunc:
test.addEventListener("click", function(){
console.log("TEST")
break testfunc
})
Here I get "TEST" everytime i click but I want it only to console.log("TEST") only once在这里,每次单击时我都会得到“TEST”,但我只希望它只显示一次 console.log("TEST")
function testfunc(){
test.addEventListener("click", function(){
console.log("TEST")
return
})
}
You cannot return testfunc
from an event in your listener since your listener anonymous function will be executed on click
event, after testfunc
is executed.您无法从侦听器中的事件返回
testfunc
,因为在执行 testfunc 之后,您的侦听器匿名testfunc
将在click
事件上执行。
What you can is prevent your event listener anonymous function to be reexecuted .您可以防止您的事件侦听器匿名 function 被重新执行。 To do so, write a condition with a variable which will be set to
true
after it is executed once.为此,请编写一个带有变量的条件,该变量在执行一次后将设置为
true
。
let isClicked = false; function testFunc(){ document.addEventListener("click", function(){ if (isClicked) return; // Will be executed once. console.log("TEST"); isClicked = true; }) } testFunc();
you can create some variable and put there flag (true/false), for example:您可以创建一些变量并在那里放置标志(真/假),例如:
let isClicked = false; function testfunc(){ test.addEventListener("click", function(){ if (isClicked) return; console.log("TEST") isClicked = true }) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.