繁体   English   中英

循环中的 clearInterval 不能按预期工作

[英]clearInterval in loop don't work as expected

我有问题当我删除字母时,单词仍然存在

我有两个 h1 我从每个 h1 中删除了单词,当所有字母都被删除时,我专门为每个 h1 停止间隔

图像

 let mySelector = document.querySelectorAll(".writ-text"); for (let l = 0; l < mySelector.length; l++) { removeText = setInterval(function() { // Cut the last letter of the word and print the word after editing document.querySelectorAll(".writ-text")[l].textContent = document.querySelectorAll(".writ-text")[l].textContent.substr(0, document.querySelectorAll(".writ-text")[l].textContent.length - 1); // Check if the entire word has been deleted if (document.querySelectorAll(".writ-text")[l].textContent.length == 0) { clearInterval(removeText) } }, 1000); }
 <h1 class="writ-text">gold</h1> <h1 class="writ-text">golder</h1>

您已经清除了唯一的名为removeText (全局范围)的setInterval ,这使得它适用于两个文本。
使用像let const这样的块 scope 来解决

 let mySelector = document.querySelectorAll(".writ-text"); for (let l = 0; l < mySelector.length; l++) { let removeText = setInterval(function() { // Cut the last letter of the word and print the word after editing document.querySelectorAll(".writ-text")[l].textContent = document.querySelectorAll(".writ-text")[l].textContent.substr(0, document.querySelectorAll(".writ-text")[l].textContent.length - 1); // Check if the entire word has been deleted if (document.querySelectorAll(".writ-text")[l].textContent.length == 0) { clearInterval(removeText) } }, 1000); }
 <h1 class="writ-text">gold</h1> <h1 class="writ-text">golder</h1>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM