javascript - 如何有效地将 javascript 链接到 html?

标签 javascript html

我正在尝试将一个 javascript 文件链接到我的 html,它将显示一个数字时钟

我已经在线检查并按照所说使用了脚本标签,但是更改没有显示在我的网页上,我需要帮助

html
 <head>
        <meta name="viewport" content="width=device-width, initial-scale=1" charset=>
        <title>About Me</title>
        <link href=".\main.css" type="text/css" rel="stylesheet">
        <script src="script.js"></script>
    </head>

java脚本

function updateClock(){
    var currentTime = new Date();
    var currentHours = currentTime.getHours();
    var currentMinutes = currentTime.getMinutes();
    var currentSeconds = currentTime.getSeconds();

    currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
    currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;

    var timeOfDay = (currentHours < 12) ? "AM" : "PM";
    currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;
    currentHours = (currentHours == 0) ? 12 : currentHours;

    var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + ":" + timeOfDay;

    document.getElementById('clock').innerHTML = currentTimeString;
};

//windows.onload=init;

最佳答案

在您的 HTML 中,尝试输入 onLoad="updateClock()"body标记或容器标记以从 JS 调用您的时钟方法。

像这样,

<div onLoad="updateClock()" class="clock"></div>

<body onLoad="updateClock()">
....
</body>

这可以通过任何标签来完成。

完整示例在这里:

https://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock

关于javascript - 如何有效地将 javascript 链接到 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56997736/

相关文章:

html - div定位正在改变有无边框

以 "vscode:"开头的 HTML 链接,用于在 Visual Studio Code 中打开文件

javascript - 多行刷卡器无法从 swiper.js 使用react

php - 如何保留文本框的值?

javascript - Div 背景色在 IE8 中不显示

javascript - ionic 2 - 动态 ionic 标题

javascript - 如何使用 JavaScript 验证下拉列表中是否未选择任何内容

javascript - 在javascript中加载选定的本地文件后如何将行存储到数组中

javascript - 模块构建失败 : SyntaxError: Unexpected token regarding quotation marks

Python file.write 在 html 标签内