简体   繁体   English

未捕获的ReferenceError:未定义XXX

[英]Uncaught ReferenceError: XXX is not defined

I made a simple digital clock in JavaScript: 我用JavaScript创建了一个简单的数字时钟:

window.onload = function runMiniClock()
{
var time = new Date();
var hours = time.getHours();
var minutes = time.getMinutes();
minutes=((minutes < 10) ? "0" : "") + minutes;
ampm = (hours >= 12) ? "PM" : "AM";
hours=(hours > 12) ? hours-12 : hours;
hours=(hours == 0) ? 12 : hours;
var clock = hours + 1 + ":" + minutes + " " + ampm;
if(clock != document.getElementById('clock').innerHTML)
document.getElementById('clock').innerHTML = clock;
timer = setTimeout("runMiniClock()",1000);
setInterval(function(){
document.getElementById("clock").innerHTML = (new Date()).toLocaleTimeString();
}, 1000);
}

This code works perfectly, but when I open the console I see an error message: 该代码可以正常工作,但是当我打开控制台时,我看到一条错误消息:

Uncaught ReferenceError: runMiniClock is not defined 未捕获的ReferenceError:未定义runMiniClock

Why does it show that error message? 为什么显示该错误消息?

Here is the demo 这是演示

Because runMiniClock is not a global function, it's a local name of the function expression that you assign to window.onload . 因为runMiniClock不是全局函数,所以它是您分配给window.onload的函数表达式的本地名称。

That eval -string you are passing to setTimeout is however evaluated in the global scope, where it does not find the function to be called. 但是,您传递给setTimeout eval -string是在全局范围内评估的,在该范围内找不到要调用的函数。 You anyway should always pass functions, not strings, to setTimeout . 无论如何,您应该始终将函数(而不是字符串)传递给setTimeout

You can fix this by using 您可以使用解决此问题

timer = setTimeout(runMiniClock, 1000);

Also, notice that you have two different functions setting the innerHTML of #clock to different values, you'll want only one of them. 另外,请注意,您有两个不同的函数将#clockinnerHTML设置为不同的值,您只需要其中一个即可。 And you're missing a few variable declarations , for ampm and timer . 而且您缺少一些用于ampmtimer 变量声明

( updated demo ) 更新的演示

To be perfectly honest i didn't spend too much time looking into this. 老实说,我没有花太多时间研究这个问题。 But your clock seems to run fine without that setTimeout call anyways? 但是如果没有setTimeout调用,您的时钟似乎运行良好?

I took it out in this js fiddle 我在这个js小提琴中把它拿出来

http://jsfiddle.net/o35arzre/5/ http://jsfiddle.net/o35arzre/5/

and the clock still runs and increments appropriately. 并且时钟仍然运行并适当地递增。

are you sure it is needed? 您确定需要吗?

var time = new Date();
var hours = time.getHours();
var minutes = time.getMinutes();
minutes=((minutes < 10) ? "0" : "") + minutes;
ampm = (hours >= 12) ? "PM" : "AM";
hours=(hours > 12) ? hours-12 : hours;
hours=(hours == 0) ? 12 : hours;
var clock = hours + 1 + ":" + minutes + " " + ampm;
if(clock != document.getElementById('clock').innerHTML) document.getElementById('clock').innerHTML = clock;
setInterval(function(){
document.getElementById("clock").innerHTML = (new Date()).toLocaleTimeString();
}, 1000);

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

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