如何从头开始创建时钟对象(Javascript)
我想使用java脚本中的get方法(即gethour、getminute、getsecond)创建一个不带out的时钟对象,并想知道如何做到这一点 如果我创建了一个带有小时、分钟和秒变量的对象,我该如何让它们自动更新呢 我只想创建一个时钟来设置时间和显示时间如何从头开始创建时钟对象(Javascript),javascript,object,Javascript,Object,我想使用java脚本中的get方法(即gethour、getminute、getsecond)创建一个不带out的时钟对象,并想知道如何做到这一点 如果我创建了一个带有小时、分钟和秒变量的对象,我该如何让它们自动更新呢 我只想创建一个时钟来设置时间和显示时间 // JavaScript Document function updateTime() { // get all parts of the current time var now = new Date();
// JavaScript Document
function updateTime() {
// get all parts of the current time
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
if(hours < 10){
hours = " " + hours
}
if(minutes < 10){
minutes = "0" + minutes
}
if(seconds < 10){
seconds = "0" + seconds
}
// splice them together into a character string named "currentTime"
var currentTime = hours + ':' + minutes + ':' + seconds;
// get the clock div
var myClock = document.getElementById('clock');
// write the currentTime string to the clock div
myClock.innerHTML = currentTime;
setTimeout("updateTime()", 1000)
}
function clock(){
var time = new Date()
var hr = time.getHours()
var min = time.getMinutes()
var sec = time.getSeconds()
var ampm = " PM "
if (hr < 12){
ampm = " AM "
}
if (hr > 12){
hr -= 12
}
if (hr < 10){
hr = " " + hr
}
if (min < 10){
min = "0" + min
}
if (sec < 10){
sec = "0" + sec
}
// splice them together into a character string named "currentTime"
var currentTime = hr + ":" + min + ":" + sec + ampm;
// get the clock div
var myClock = document.getElementById('clock12');
// write the currentTime string to the clock div
myClock.innerHTML = currentTime;
setTimeout("clock()", 1000)
}
function setClock(){
var time = new Date()
var hr = time.getHours()
var min = time.getMinutes()
var sec = time.getSeconds()
var ampm = " PM "
if (hr < 12){
ampm = " AM "
}
if (hr > 12){
hr -= 12
}
if (hr < 10){
hr = " " + hr
}
if (min < 10){
min = "0" + min
}
if (sec < 10){
sec = "0" + sec
}
// splice them together into a character string named "currentTime"
var currentTime = hr + ":" + min + ":" + sec + ampm;
// get the clock div
var myClock = document.getElementById('setClock');
// write the currentTime string to the clock div
myClock.innerHTML = currentTime;
setTimeout("setClock()", 1000)
}
如果不使用Date对象,就无法使时钟显示实时。但是,如果你只是想为一个游戏或其他相关的东西制作一个任意的时钟,你可以这样做:
var clock = {
hours: 0,
minutes: 0,
seconds: 0
}
function updateTime(part, max) {
return function(){
clock[part]++
if (clock[part] > max) clock[part] = 0
}
}
setInterval(updateTime('hours', 24), 60*60*1000)
setInterval(updateTime('minutes', 60), 60*1000)
setInterval(updateTime('seconds', 24), 1000)
我的第一步是尝试。就像字面上的任何东西一样。什么get方法??你的语法java脚本,get方法表明你没有读过任何关于Javascript的介绍性材料。好吧,很抱歉我编辑了一个糟糕的问题,我想你可以在那里找到一些提示:你知道有什么方法可以更新时间吗。假设我想设置时间并实时运行时钟