Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
Setting button.onclick via button click activates on first button press

So I'm trying to create a button that when pressed changes the content of an html page and updates the button to change its next function. However, whenever I use .onclick I end up printing the "2" to the console while still on the first press of the button. I've tried using .click as well, and the only thing that I can find that works is setting the function directly, however this is untidy and long. I wondered if there was another way to do this with cleaner code.

html:

<!DOCTYPE html>
<html lang="en-US">
  <body>
    <script src="Path_To_File"></script>

      <p id="text">
        <!-- text here -->
      </p>

    <button id="b1" type="button" onclick="pageFlip(1)">Button</button>
  </body>
</html>

JS:

function pageFlip(page) {
  var p = document.getElementById("text");
  var b1 = document.getElementById("b1");
  var b2 = document.getElementById("b2");

  switch (page) {
    case 1:
      p.innerHTML = "newText";
      b1.innerHTML = "newText";
      b1.onclick = pageFlip(2);
      break;
    case 2:
      console.log("2");
      break;
  }
}

What works:

b1.onclick = function changeButton() {
    pageFlip(2)
}
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda