【问题标题】:Why is my page not loading the function properly to show the live digital clock time?为什么我的页面没有正确加载显示实时数字时钟时间的功能?
【发布时间】:2022-11-27 02:45:06
【问题描述】:

这是我的名为 index.html 的 html 文件,位于项目中的单独文件夹中。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href={{ url_for('static', filename='styles/style.css') }}>
    <meta name="viewport" content=
        "width=device-width,
        initial-scale=1.0" />

    <title>Digital Clock</title>
</head>

<body>
    <div id="clock">00:00:00</div>

    <script type="text/javascript" src= '/script.js'></script>
    <script>
        showTime();
    </script>
    
</body>

</html>

这是我的外部 javascript 文件和我的函数,它位于根目录之外。

function showTime() {
    let time = new Date();
    let hour = time.getHours();
    let min = time.getMinutes();
    let sec = time.getSeconds();
    am_pm = "AM";
 
    if (hour > 12) {
        hour -= 12;
        am_pm = "PM";
    }
    if (hour == 0) {
        hr = 12;
        am_pm = "AM";
    }
 
    hour = hour < 10 ? "0" + hour : hour;
    min = min < 10 ? "0" + min : min;
    sec = sec < 10 ? "0" + sec : sec;
 
    let currentTime = hour + ":" + min + ":" + sec + am_pm;
 
    document.getElementById("clock").innerText = currentTime;
    document.getElementById("clock").textContent = currentTime;

    setTimeout(showTime, 1000);
}

showTime();

我以为我加载了 js 文件然后正确调用它,但我的本地主机仍然只显示开头 00:00:00 并且它没有更新或工作?请帮助我大声笑。

【问题讨论】:

  • 您如何为页面提供服务?

标签: javascript html


【解决方案1】:

你的代码工作正常。你确定文件正在加载吗?在开发工具中检查网络

function showTime() {
    let time = new Date();
    let hour = time.getHours();
    let min = time.getMinutes();
    let sec = time.getSeconds();
    am_pm = "AM";
 
    if (hour > 12) {
        hour -= 12;
        am_pm = "PM";
    }
    if (hour == 0) {
        hr = 12;
        am_pm = "AM";
    }
 
    hour = hour < 10 ? "0" + hour : hour;
    min = min < 10 ? "0" + min : min;
    sec = sec < 10 ? "0" + sec : sec;
 
    let currentTime = hour + ":" + min + ":" + sec + am_pm;
 
    document.getElementById("clock").innerText = currentTime;
    document.getElementById("clock").textContent = currentTime;

    setTimeout(showTime, 1000);
}

showTime();
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href={{ url_for('static', filename='styles/style.css') }}>
    <meta name="viewport" content=
        "width=device-width,
        initial-scale=1.0" />

    <title>Digital Clock</title>
</head>

<body>
    <div id="clock">00:00:00</div>

    <script type="text/javascript" src= '/script.js'></script>
    
    
</body>

</html>

【讨论】:

  • 如果代码有效,您应该将问题标记为“问题不可重现”。
猜你喜欢
  • 2015-09-05
  • 1970-01-01
  • 2020-10-11
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多