我正在尝试在HTML页面中使用当前的月,年,月-年和日-月。
这是我正在使用的javascript
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var n = new Date();
var y = n.getFullYear();
var m = n.getMonth();
var d = n.getDate();
document.getElementById("date").innerHTML = d + " " + months[m] + " " + y;
document.getElementById("month-year").innerHTML = months[m] + " " + y;
document.getElementById("day-month").innerHTML = d + " " + months[m];
document.getElementById("year").innerHTML = y;
document.getElementById("month").innerHTML = months[m];
document.getElementById("day").innerHTML = d;
I'm using an html <a>
tag to call the date, month, year etc, as follows
<a id="date"></a>
<a id="month-year"></a>
<a id="day-month"></a>
<a id="year"></a>
<a id="month"></a>
<a id="day"></a>
However it only works when I use <a id="date"></a>
somewhere in the page, if I don't use <a id="date"></a>
then none of the other tags work.
I've created a jsfiddle to highlight the problem. If you remove <a id="date"></a>
from the Html section you'll see the problem I'm referring to.
这是因为您的javascript由于存在null对象而中断
You should check whether it exists before setting the
innerHTML
. For example: