我正在制作一个用于学习的计数器应用程序,在给计数器名称后,计数器在 onclick 事件中递增 1 这在只有计数器时工作正常但如果我添加多个名称它会在新计数器上采用最后一个增量值,基本上每个新创建的计数器的增量应该是分开的。let counter = 0function updateCount() { let progressCountUpdate = document.getElementsByClassName("progress-count") for (var i = 0; i < progressCountUpdate.length; i++) { progressCountUpdate[i].onclick = function () { this.childNodes[1].innerText = counter++ } }}function createProgress() { progressCount = document.createElement("div") progressCount.className = "progress-count" progressNameNew = document.createElement("span") progressNameNew.innerText = progresslabel.value; progressNameNew.className = 'progress-name' progressCountNumber = document.createElement("span") progressCountNumber.innerText = 0 progressCountNumber.className = "progress-counter" progressCount.appendChild(progressNameNew) progressCount.appendChild(progressCountNumber) progressDisplay.appendChild(progressCount) progresslabel.value = "" updateCount()}addbutton.onclick = function () { if (progresslabel.value === "") { alert("enter progress name") } else { checkStartEndTime(); createProgress(); }}<div class="progress-display"></div>如何确保每个计数器的增量都是独立的。
1 回答
HUWWW
TA贡献1874条经验 获得超12个赞
您可以创建一个闭包函数,以便为每个单独的onclick函数添加一个计数器,如下所示:
function updateCount() {
let progressCountUpdate = document.getElementsByClassName("progress-count");
for (let el of progressCountUpdate) {
if (el.getAttribute('hasOnClick') !== 'true') {
el.onclick = (function() {
const childNode = el.childNodes[1];
let counter = 0;
el.setAttribute('hasOnClick', 'true'); // set a flag so it won't reset every update
return function() {
return childNode.innerText = counter++;
}
})();
}
}
}
添加回答
举报
0/150
提交
取消