让计数= document.querySelector(".count");
设dropBtn =document.querySelector(“.”);
设resetBtn =document.querySelector(“.”);
设addBtn =document.querySelector(“.”);
AddBtn.addEventListener(“单击”,函数() {
设add = 0;
对于(设i= 0;i;i++) count.textContent =添加+= 1;
});
发布于 2022-03-05 06:10:28
为此,我喜欢闭包。侦听器调用一个函数,该函数设置默认的add
变量,并返回一个新函数,该函数充当单击按钮时调用的函数。这样你就没有任何全局变量了。基本上,闭包是在返回变量时从其“外部词法作用域”携带变量的函数。
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>
发布于 2022-03-05 05:54:43
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>
https://stackoverflow.com/questions/71359825
复制相似问题