You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js运行前端代码出现ReferenceError: document is not defined问题

问题:Node.js环境运行秒表代码报“document is not defined”错误

在Node.js环境中运行秒表代码,此前从未出现问题,但现在持续提示指向DOM元素的变量报错“document is not defined”。已尝试将脚本放在页面底部、顶部并添加defer属性,问题仍未解决。相关代码如下:

JS代码

let seconds = 00;
let tens = 00;
let appendTens = document.querySelector('#tens');
let appendSeconds = document.querySelector('#seconds');
let stop = document.querySelector('#button-stop');
let start = document.querySelector('#button-start');
let reset = document.querySelector('#button-reset');
let interval; //store timer values


// this function will run when start is clicked 

const startTimer = () =>{
    tens++

    if(tens < 9){
        appendTens.textContent = `0${tens}`
    }
    if(tens > 9){
        appendTens.textContent = tens;
    }
    if(tens > 99){
        seconds++
        appendSeconds.textContent = `0${seconds}`;
        tens = 0;
        appendTens.textContent = "0" + 0;
    }
    if(seconds > 9){
        appendSeconds.textContent = seconds;
    }
};

start.onclick = function(){
    interval = setinterval(startTimer)
}

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stopwatch</title>
    <link rel="stylesheet" href="stopwatch.css">
</head>
<body>
    <div class="wrapper">
        <h1>Stopwatch</h1>
        <h2>Vanilla JavaScript Stopwatch</h2>
        <p><span id="seconds">00</span>:<span id="tens">00</span></p>
        <button id="button-start">Start</button>
        <button id="button-stop">Stop</button>
        <button id="button-reset">Reset</button>
        </div> 
        <script type="module" src="stopwatcj.js"></script>
</body>
</html>

CSS代码

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  justify-content: center;
  align-self: center;
  background-color: rgb(248, 180, 55);
}

.wrapper {
  margin-top: 10%;
  text-align: center;
  color: #fff;
}
.wrapper button {
  background-color: rgb(248, 180, 55);
  border: 1px solid white;
  padding: 10px 20px;
  color: #fff;
}
.wrapper button:hover {
  cursor: pointer;
  opacity: 30%;
}

内容的提问来源于stack exchange,提问作者Angel94124

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 17:30:59