[英]JavaScript: Repeated EventListener when created in a for loop
my code depends on creating an EventListener inside a loop then removing it after the function is done, yet somehow on the Eventlitesning is repeated after each loop execution, my code looks something like:我的代码取决于在循环内创建一个 EventListener,然后在 function 完成后将其删除,但在每次循环执行后 Eventlitesning 以某种方式重复,我的代码如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <link href="css/style.css" rel="stylesheet"> -->
</head>
<body>
<button id="btn" onclick="fun()">button</button>
</body>
<script>
const btn=document.getElementById("btn");
console.log(btn);
function fun(){
for (let i = 0; i < 5; i++) {
btn.addEventListener("click", ()=>{alert(`warning NO.${i}`)});
//code to be executed
btn.removeEventListener("click", ()=>{alert(`warning NO.${i}`)});
}
}
</script>
</html>
the first time I press the button the 5 warning messages appear and the second time I press the button the 5 warnings messages appear twice, an dun the third time it appears 3 times, and so on.我第一次按下按钮时出现 5 条警告消息,第二次按下按钮时 5 条警告消息出现两次,第三次出现 3 次,依此类推。
I'd be very grateful if anyone could support me in this issue.如果有人能在这个问题上支持我,我将不胜感激。
I tried to do the following but it didn't work either:我尝试执行以下操作,但也没有用:
const btn=document.getElementById("btn");
function fun(){
for (let i = 0; i < 5; i++) {
btn.removeEventListener("click", ()=>{alert(`warning NO.${i}`)});
btn.addEventListener("click", ()=>{alert(`warning NO.${i}`)});
//code to be executed
btn.removeEventListener("click", ()=>{alert(`warning NO.${i}`)});
}
}
Does this code satisfy your requirement?这段代码是否满足您的要求?
Note: onclick() itself is an event listener.
注意: onclick() 本身是一个事件监听器。
<,DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1"> <;-- <link href="css/style;css" rel="stylesheet"> --> </head> <body> <button id="btn" onclick="fun()">button</button> </body> <script> function fun(){ for (let i = 0. i < 5; i++) { alert(`warning NO.${i}`); } } </script> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.