我正在尝试使用javascript构建一个简单的时钟,但我不知道为什么它不起作用。
$(document).ready(function() {
function updateTime() {
var now = newDate();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var currenTime = hours + ':' + minutes ':' + seconds;
var counter = document.getElementById('counter');
counter.innerHTML = currentTime;
}
updateTime();
});
答案 0 :(得分:2)
首先,您需要修复代码中的错误:
new
和Date
之间的空格(new Date
)。var currenTime
中的拼写错误 - > var currentTime
+
minutes
之后遗失var currentTime
醇>
稍后,如果您想制作实时时钟,则需要使用setInterval
每秒拨打updateTime
。
setInterval(updateTime, 1000);
喜欢这个。
当然在你的html中定义<div id="counter"></div>
。
$(document).ready(function() {
function updateTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var currentTime = hours + ':' + minutes + ':' + seconds;
var counter = document.getElementById('counter');
counter.innerHTML = currentTime;
}
updateTime();
setInterval(updateTime, 1000);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter"></div>
&#13;
答案 1 :(得分:1)
newDate()// wrong
应该是新的Date();
counter.innerHTML = currenTime;
应为counter.innerHTML = currentTime;
使用setInterval
$(document).ready(function() {
var counter = document.getElementById('counter');
window.setInterval(function() {
console.log(1);
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var currentTime = hours + ':' + minutes +':' + seconds;
counter.innerHTML = currentTime;
}
,'1000');
});
答案 2 :(得分:0)
您错过了new
和Date()
之间的空白区域。在此之前你真的应该看一下devtools。
你的功能在DOM就绪时执行,就完成了。你想要的是每秒更新一次。您需要setInterval
或重复setTimeout
。
答案 3 :(得分:0)
function countdown(id, timer){
timer--;
daysRemain = Math.floor(timer / 86400);
amount = timer%86400;
hrsRemain = Math.floor(amount / 3600);
amount = timer%3600;
minsRemain = Math.floor(amount/60);
amount = timer%60;
secsRemain =Math.floor(amount);
// Pad the string with leading 0 if less than 2 chars long
if (secsRemain.length < 2) {
secsRemain = '0' + secsRemain;
}
// String format the remaining time
clock = daysRemain + ":" + hrsRemain + ":" + minsRemain + ":" + secsRemain;
document.getElementById(id).innerHTML = clock;
if ( timer > 0 ) {
// Time still remains, call this function again in 1 sec
setTimeout("countdown('" + id + "'," + timer + ")", 1000);
} else {
// Time is out! Hide the countdown
document.getElementById(id).innerHTML = 'Time Expired';
}
}
这是使用javascript创建计时器时钟的另一种方式