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("clic", función () {
vamos a sumar = 0;
for (let i = 0; i ; i++) count.textContent = add += 1;
});
Me gustan los cierres para esto. Su oyente llama a una función que configura una variable de add predeterminada y devuelve una nueva función que actúa como la función que se llama cuando se hace clic en el botón. De esta manera no tienes ninguna variable global. Básicamente, los cierres son funciones que transportan las variables desde su "ámbito léxico externo" cuando se devuelven.
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> 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>