我知道这可能是一个非常新手的问题,但是我似乎无法在任何地方在线找到答案,也无法理解为什么会这样。因此,冒着被低估的风险...我希望在这里找到答案。
我几乎可以按照自己的意愿来运行代码,但是我不想使用任何全局变量。但是,每当我将此变量放入任何函数中时,代码就会停止工作。
我将不胜感激。抱歉,这个问题被问了一千遍了。他们以这种方式了解全局/本地绑定-这不应该发生吗?
这是我的代码,其中有注释,无论我在哪里放置变量而不是在函数顶部。
谢谢。
<body> <div class="style" onclick="typeWriter()"> <p id="remove">Hide Me</p> <p id="type"></p> </div> </body>
// Javascript
let letCounter = 0; //Do not want this as a global variable
function hideInitText() {
let hide = document.getElementById("remove");
hide.classList.add("hide");
//let letCounter = 0; //I tried here
}
hideInitText();
function typeWriter() {
//let letCounter = 0; //I tried here
let cycle, classCounter; //establish the cycle and counter
cycle = document.querySelectorAll("#type"); //cycle includes the .type class
for (classCounter = 0; classCounter < cycle.length; classCounter++) { //for loop that actually cycles
//let letCounter = 0; //I tried here
typeOut();
}
function typeOut() {
//let letCounter = 0; //I tried here
let speed = 50; //speed in milliseconds
let typewriter = "Type me out"; //document.querySelectorAll(".type");
if (letCounter < typewriter.length) {
//let letCounter = 0; //I tried here
//hide.classList.remove("hide"); //unhide the text
cycle[classCounter].innerHTML += typewriter.charAt(letCounter);
letCounter++;
setTimeout(typeWriter, speed);
}
}
};
我知道这可能是一个非常新手的问题,但是我似乎无法在任何地方在线找到答案,也无法理解为什么会这样。因此,冒着被低估的风险...我希望找到...
对于您要每次增加该值的情况,函数都需要一个全局变量。
一个问题是