我正在编写一个快捷方式 JavaScript 文件来制作$date
和$time
变量。据我所知,它应该可以工作,但它不会显示并且 Google Chrome 的调试器会显示[Uncaught TypeError: Cannot Read 'firstChild' of null]
这是我的代码:
function mdy(){
var
h = new Date(),
year = h.getFullYear(),
month = h.getMonth() + 1,
day = h.getDate();
if(month < 10) { month = "0" + month; }
if(day < 10) { month = "0" + month; }
var string = month + "/" + day + "/" + year;
document.getElementById('mdy').firstChild.nodeValue = string;
}
function ymd(){
var
h = new Date(),
year = h.getFullYear(),
month = h.getMonth() + 1,
day = h.getDate();
if(month < 10) { month = "0" + month; }
if(day < 10) { month = "0" + month; }
var string = year + "/" + month + "/" + day;
document.getElementById('ymd').firstChild.nodeValue = string;
}
var $date = {
mdy: '<span id="mdy"> </span>',
ymd: '<span id="ymd"> </span>'
}
/* $time module */
// this comes in two formats, standard and military.
// type $time.standard for standard time and $time.military
// for military time
function tstandard(){
var
h = new Date(),
hours = h.getHours(),
minutes = h.getMinutes();
minutes = ( minutes < 10 ? "0" : "" ) + minutes;
var diem = ( hours < 12 ) ? "am" : "pm";
hours = ( hours > 12 ) ? hours - 12 : hours;
hours = ( hours == 0 ) ? 12 : hours;
var string = hours + ":" + minutes + " " + diem;
document.getElementById("tstandard").firstChild.nodeValue = string;
}
function tmilitary() {
var
h = new Date(),
hours = h.getHours(),
minutes = h.getMinutes();
minutes = ( minutes < 10 ? "0" : "" ) + minutes;
hours = ( hours == 0 ) ? 12 : hours;
if(hours < 10) { hours = "0" + hours }
var string = hours + ":" + minutes;
document.getElementById("tmilitary").firstChild.nodeValue = string;
}
var $time = {
standard: "<span id='tstandard'> </span>",
military: "<span id='tmilitary'> </span>"
}
/*! universal body onload function !*/
window.onload = function(){
mdy(); setInterval('mdy()', 1000);
ymd(); setInterval('ymd()', 1000);
tstandard(); setInterval('tstandard()', 1000);
tmilitary(); setInterval('tmilitary()', 1000);
}
在我的 HTML 中,我正在做:
<script>document.write($date.mdy + " - " + $time.standard);</script>