简体   繁体   中英

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:

<!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.

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?
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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM