为什么此“未捕获的ReferenceError:速度未定义"?错误? [英] Why this "Uncaught ReferenceError: tempo is not defined" error?
问题描述
我有以下代码:
$("#avvia_cronometro").click(function() {
var tempo = setInterval(function() {
cronometro();
$("#tempo_cronometro").html((h)+":"+(min)+":"+(sec));
}, 1000);
});
$("#stop_cronometro").click(function() {
clearInterval(tempo);
});
function cronometro() {
if (sec == 59) {
min +=1;
if (min == 59) {
h+=1;
min=0;
}
sec=0;
}
sec+=1;
}
当我单击#stop_cronometro
时,它不起作用,并显示:
When I click on #stop_cronometro
it doesn't work and it says:
Uncaught ReferenceError: tempo is not defined
我该如何解决?
如果我单击#avvia_cronometro
,它会从时间开始,因此可以正常工作.
If I click on #avvia_cronometro
it starts with the time so it's work.
推荐答案
因为全局范围(或停止点击处理程序可以到达的任何范围)中不存在变量tempo
.
Because there is no variable tempo
that exist in global scope (or any scope that the stop click handler can reach).
当您在函数内部使用var
声明变量时,该变量将在该函数返回时被删除:
When you declare a variable with var
inside a function that variable gets deleted when the function returns:
function foo () {
var bar = 1;
}
foo();
console.log(bar); // uncaught reference error - "bar" doesn't exist
如果需要全局变量,请在不使用var
的情况下使用它:
If you need a global variable, use it without the var
:
function foo () {
bar = 1;
}
foo();
console.log(bar); // prints 1
但是,我通常不建议这样做,因为这对于将来的维护者来说似乎是一个错误.而是在全局范围内显式声明全局变量,以清楚地表明您的意图:
However, I would generally not recommend this since it looks like an error to future maintainers. Instead, declare the global variable explicitly in global scope to clearly show your intention:
var bar = null;
function foo() {
bar = 1;
}
foo();
console.log(bar); // prints 1
这篇关于为什么此“未捕获的ReferenceError:速度未定义"?错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!