问题
I'm trying to display the current month and year, but nothing is being displayed.
HTML:
<div id="date"></div>
CSS:
#date {
display: block;
color: black;
font-size: 50px;
top: 50px;
left: 50px;
}
JavaScript:
(function() {
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
Date.prototype.getMonthName = function() {
return months[ this.getMonth() ];
};
Date.prototype.getDayName = function() {
return days[ this.getDay() ];
};
})();
var now = new Date();
var day = now.getDayName();
var month = now.getMonthName();
回答1:
You need to connect your JS to your HTML. This is done via the DOM.
First, you need to get the Date div, then use your day and month values to insert the data into the div.
Add these two lines to the bottom of your JS, and you'll see the date and month.
var date_div = document.getElementById("date")
date_div.innerHTML = day + "," + month
回答2:
document.getElementById("date").innerHTML = month;
回答3:
is this what you are looking for?
(function() {
var date = new Date();
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
document.getElementById('date').innerHTML = months[date.getMonth()] + ' ' + months[date.getDay()]
})();
#date {
display: block;
color: black;
font-size: 50px;
top: 50px;
left: 50px;
}
<div id="date"></div>
回答4:
You can even use
document.querySelector("#date").insertAdjacentHTML("afterbegin",day+","+month)
but be careful this will not clear the already available content in the date div
回答5:
Hello Please try this is the working code.
JS
(function() {
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
Date.prototype.getMonthName = function() {
return months[ this.getMonth() ];
};
Date.prototype.getDayName = function() {
return days[ this.getDay() ];
};
})();
var now = new Date();
document.getElementById('date').innerHTML = now.getDayName() + "-" + now.getMonthName();
Html
<div id="date"></div>
Here is the jsFiddle
来源:https://stackoverflow.com/questions/57139093/month-and-year-not-displaying