javascript - 函数已定义但仍未定义

标签 javascript html setinterval increment stopwatch

我正在尝试用 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/

相关文章:

Javascript OnPageUnload - 在 "leave page"上必须调用附加方法

javascript - 使用 jQuery 更改 YouTube iframe src

html - 谷歌浏览器上 video.js 的视频重播问题

html - 对齐联系表中的输入框 7

javascript - Web worker 使 setInterval 正常工作

JavaScript - jQuery 区间

jquery 图像 slider setInterval 问题

javascript - 点击后隐藏div

javascript - 构建拖放导航选项卡

javascript - React 组件是否深入比较 props 以检查是否需要重新渲染?