我正在尝试将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;
答案 0 :(得分:4)
在HTML中,尝试将onLoad="updateClock()"
放在body
标记或容器标记中,以从JS调用您的Clock方法。
喜欢这个
<div onLoad="updateClock()" class="clock"></div>
OR
<body onLoad="updateClock()">
....
</body>
这可以通过 any 标签完成。
完整示例在这里:
https://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock
答案 1 :(得分:0)
很多问题。
首先,在您的头脑中,将字符集值设置为某种值或摆脱它。我指的是<meta name="viewport" content="width=device-width, initial-scale=1" charset=>
。
第二,需要在调用javascript之前加载html。要解决此问题,请将脚本放在</body>
标记之前的底部,或者将<body>
更改为<body onload="updateClock()">
。如果您是第一种方式,请确保调用您的函数;否则,什么都不会发生。
最后,您需要添加div标签或ID为“ clock”的内容;否则您的document.getElementById('clock').innerHTML
将无能为力。
总摘要:
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;
};
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>About Me</title>
</head>
<body onload="updateClock()">
<div id="clock"></div>
</body>