我正在尝试用 js 制作秒表,并且我的代码工作正常,直到我在秒表中包含毫秒。
这是我的代码:
index.html
<html>
<head>
<title>My Second Page</title>
<script src="script.js"></script>
</head>
<body>
<input type="button" onclick="gettime()" value="Start Stopwatch"></a>
</body>
</html>
脚本.js
var ss = 0,
mm = 0,
hh = 0,
ms = 0;
var once = 0;
function gettime() {
if (once == 0) {
document.write('<h1 id="stopwatch"></h1>');
once++;
}
setInterval("msss()", 100);
}
function msss() { // I have defined msss
printtime();
if (ms > 1000) {
sec();
} else {
ms += 100;
}
}
function sec() {
ms = 0;
printtime();
if (ss > 59) {
min();
} else {
ss += 1;
}
}
function min() {
ss = 0;
printtime();
if (mm > 59) {
hr();
} else {
mm += 1;
}
}
function hr() {
mm = 0;
printtime();
hh += 1;
}
function printtime() {
document.getElementById('stopwatch').innerHTML = 'H: ' + hh + 'M: ' + mm + ' S: ' + ss + ' MS: ' + ms;
}
错误代码
ReferenceError: msss is not defined
我做错了什么?
最佳答案
问题是你的document.write()
。使用这个是一个不好的做法。发生的情况是,当调用此函数时,页面将被完全删除,并替换为代码。
这会删除页面上的所有内容,包括 JavaScript。因此,mss
不再存在,因为您刚刚删除了它。
这已在您之前的问题 ( https://stackoverflow.com/a/25398255 ) 的回答中得到解释。
尝试如下:
document.body.innerHTML = '<h1 id="stopwatch"></h1>';
关于javascript - 函数已定义但仍未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25410492/