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

166
Visualizações
JavaScript / HTML work with DOM, Button which count click and make new string every time when I click

I need create button which count click but make every time new string. I have that function with scope which make count every time when I click, but I cannot understand, why in HTML it every time count zero, should be like this: (Verticaly every click make new string with updated count) 1 2 3 4 ...

<form action="#">
    <input type="button" value="Count" onclick="add_count()">
</form>

function add_count() {
let integer = (function () {
    let counter = 0;
    return function() {return counter++;};
}());
let tag = document. createElement("p");
let text;
text = document. createTextNode(integer());
tag. appendChild(text);
let element = document. getElementsByTagName("body")[0];
element. appendChild(tag)};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You just need to move the counter initialization outside of the function scope

I've tweaked your code a bit.

Note: try not using inline event listeners, instead use event listeners in JavaScript file

let counter = 0;

const button = document.querySelector('input');

function add_count() {
  let integer = (() =>  counter++);
  const tag = document.createElement("p");
  const text = document.createTextNode(integer());
  tag.appendChild(text);
  const element = document.body
  element.appendChild(tag)
};

button.addEventListener('click', add_count)
<form action="#">
  <input type="button" value="Count">
</form>

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