Do not trade players

Asked

Viewed 31 times

0

In my program the player always stays in "player 1". Does anyone know why?

<span id="info_jogador" style="visibility: hidden">Jogador: <span id="jogador">1</span></span>

//script

if (jogador == 1)
{

   document.getElementById("b" + pos + "-" + coluna).src = img_blue;            
   jogador = 2;
   name = img_blue;
}
else
{
    document.getElementById("b" + pos + "-" + coluna).src = img_red;            
    jogador = 1;
    name = img_red;
}
  • Have you ever given a console.log() on this 'player'? Checked the type?

  • @I don’t know what you meant. But I already gave console.log("hello") for example, and the program is coming to that part, if I made myself aware.

  • What is this jogador 1 that you mentioned? Is the player variable? Is some element of the DOM with the internal HTML "player"? From your code you can’t tell what the problem is, try to describe more of what’s going on.

  • @user140828 player is like a "label", what varies is only 1 and 2. But at this point the program keeps if only in 1

1 answer

1

Okay, "Player" refers to HTML, but there is no manipulation in the DOM for the value displayed to the user to be changed. There is only one variable with the same name receiving values, but this will not reflect in HTML.

To modify HTML, you need to search the DOM element with something like getElementById, and then change the desired property, in this case the internal HTML.

function alteraJogador()
{
  const jogador = document.getElementById('jogador');
  
  if (jogador.innerHTML == 1)
  {          
     jogador.innerHTML = 2;
  }
  else
  {         
      jogador.innerHTML = 1;
  }
}

// chama a função alteraJogador a cada segundo
setInterval(alteraJogador, 1000);
<span id="info_jogador">Jogador: <span id="jogador">1</span></span>

  • @user14028 thanks for the help, I have already solved the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.