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

221
Visualizações
I am making a counter in javascript. Can someone tell me how to 'loop' here so that the counter could increase everytime somone clicks the button

let count = document.querySelector(".count");

let dropBtn = document.querySelector(".btn-drop");

let resetBtn = document.querySelector(".btn-reset");

let addBtn = document.querySelector(".btn-add");

addBtn.addEventListener("click", function () {

let add = 0;

for (let i = 0; i ; i++) count.textContent = add += 1;

});

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I like closures for this. Your listener calls a function that sets up a default add variable, and returns a new function that acts as the function that's called when the button is clicked. This way you don't have any global variables. Basically closures are functions that carry the variables from their "outer lexical scope" when they get returned.

const count = document.querySelector('.count');
const addBtn = document.querySelector('.btn-add');

// Call a function that returns a new function that works
// as the click handler
addBtn.addEventListener('click', handleClick(), false);

// Initialise `add` with an initial default value
function handleClick(add = 0) {

  // Return a function that is called when the
  // button is clicked. That function (closure) will keep
  // a record of the `add` variable,
  // and update the content with its value when the button is clicked
  return function() {
    count.textContent = ++add;
  }

}
<div class="count">0</div>
<button class="btn-add">Update counter</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

let addBtn = document.querySelector(".btn-add");

addBtn.addEventListener("click", function () {
  let count_element = document.querySelector(".count"); //select element with class "count"
  count = parseInt(count_element.innerText); //parse the text inside count_element to int
  count = count || 0; //if count Not a number, initial value of count is 0;
  count = count +1; //add 1 to counter
  count_element.innerText = count; //change count_element text to count
});
<button class="btn-add">ADD</button>
<div class="count">NaN</div>

about 4 years ago · Juan Pablo Isaza Relatório
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