Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

109
Vistas
Why is my addEventListener going off over and over again?

This double for loop is supposed to loop over a Battleship board and add an event listener to each cell. The event listener is supposed to represent a cell in a Battleship board. When it is clicked and a ship is positioned on that cell, the cell's color will change to red, representing a hit, and w will increment by 2. If w reaches 24, the game will end and the winner's scores will be presented.

let table2 = document.getElementById("player2board");
        let opptable2 = document.getElementById("player1opp");
        for(var i = 1; i < table2.rows.length; i++){
          for(var j = 1; j < table2.rows[i].cells.length; j++){
            table2.rows[i].cells[j].innerHTML = p2Board[i - 1][j - 1];
            if(p2Board[i - 1][j - 1] != ""){
              let currcell = opptable2.rows[i].cells[j];
              opptable2.rows[i].cells[j].addEventListener("click", () => {currcell.style.backgroundColor = "Red";
              document.getElementById("player1table").hidden = true;
              w += 2;
              console.log(w);
              if(w == 24){
                let t = w;
                w = w - w2;
                w2 = w2 - t;
                document.getElementById("p1score").innerText = p1Name + "'s score (winner): " + w;
                document.getElementById("p2score").innerText = p2Name + "'s score: " + w2;
                document.getElementById("scores").hidden = false;
              }else{
                document.getElementById("player2turn").hidden = false;
              }});
            }else{
              let currcell = opptable2.rows[i].cells[j];
              opptable2.rows[i].cells[j].addEventListener("click", () => {currcell.style.backgroundColor = "White";
              document.getElementById("player1table").hidden = true; document.getElementById("player2turn").hidden = false;});
            }
          }
        }

What's going wrong, though, is that the event listener is incrementing w for every hit that has been made. If I click on a cell and get a 2nd hit, w will increment by 4, if I get a 3rd hit w will increment by 8 etc. What did I do wrong and how do I fix it?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda