[英]How do I effectively link javascript to 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中,嘗試在body
標簽或容器標簽中放置onLoad="updateClock()"
以從JS調用您的clock方法。
像這樣,
<div onLoad="updateClock()" class="clock"></div>
要么
<body onLoad="updateClock()">
....
</body>
可以使用任何標簽來完成。
完整示例如下:
https://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock
很多問題。
首先,將您的charset值設置為某個值或擺脫它。 我要指的問題是<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.