[英]Why isn't my global variable available within my function?
When you run a script, I noticed the variables you write out get run only once. 当您运行脚本时,我注意到您写出的变量只运行一次。 Functions on the other hand, can be called multiple times.
另一方面,功能可以被多次调用。
Is there a way to call up a variable more than once like you can functions? 有没有办法像函数一样多次调用一个变量? Sorry no code for this one, just a question.
对不起这个没有代码,只是一个问题。
Edit: To clarify, I have a global variable that is used for a function. 编辑:为了澄清,我有一个用于函数的全局变量。 However when I try to call this variable from a seperate function, it does not register because it is now considered "local".
但是,当我尝试从单独的函数调用此变量时,它不会注册,因为它现在被视为“本地”。
However, if I could call up the global variable at will, then I believe this would fix the issue. 但是,如果我可以随意调用全局变量,那么我相信这会解决问题。
// BLITZ SKILL // <-- My 2nd Function trying to use my global variable counter
document.getElementById("blitz").addEventListener('click', function(){
var counter = setInterval(timer, 1000); // Trying to restart timer, does
// not register counter variable.
var damage = Math.floor(Math.random() * characterstats.strength);
document.getElementById("energy").innerHTML = character.energy;
if ((damage <= 0) && (character.energy >= 5)) {
addMessage("You miss the dragon!");
character.energy -= 5;
}
else if (character.energy <= 4) {
addMessage("Not enough energy!")
}
if ((damage >= 1) && (character.energy >= 5)) {
dragon.hp -= damage;
document.getElementById("npchp").innerHTML = dragon.hp;
addMessage("You hit the dragon for " + damage + " hp!");
character.energy -= 5;
}
document.getElementById("energy").innerHTML = character.energy;
});
// 7. CODE TESTING AREA
var counter = setInterval(timer, 1000); <-- MyGlobal Variable
function timer() { //
var count = character.energy;
count += characterstats.energyregen;
if (count >= 35) {
clearInterval(counter);
}
document.getElementById("energy").innerHTML = count;
character.energy = count;
}
You are creating a new local variable called counter in your function by using var. 您正在使用var在函数中创建一个名为counter的新局部变量。
Just reference the global like so without using "var" which defines a new variable, 只需引用全局,不要使用定义新变量的“var”,
document.getElementById("blitz").addEventListener('click', function(){
counter = setInterval(timer, 1000); // <-- Trying to restart timer, does not
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.