我无法以以下格式显示日期:
“今天是星期五,即 2019 年 6月的第29 天。”
我正在HTML5文档中使用JavaScript。我已经提供了代码,非常感谢您的协助。除了基础级JavaScript可以完成的工作外,我不想为此使用任何第三方库。
<script type="text/javascript">
<!--
var monthName = new Array();
monthName[0] = "January";
monthName[1] = "February";
monthName[2] = "March";
monthName[3] = "April";
monthName[4] = "May";
monthName[5] = "June";
monthName[6] = "July";
monthName[7] = "August";
monthName[8] = "September";
monthName[9] = "October";
monthName[10] = "November";
monthName[11] = "December";
var myYear = today.getFullYear();
var myDate = today.getDate();
var dayExt = "th";
if ((myDate == 1) || (myDate == 21) || (myDate == 31)) dayExt = "st";
if ((myDate == 2) || (myDate == 22)) dayExt = "nd";
if ((myDate == 3) || (myDate == 23)) dayExt = "rd";
var extDate = myDate + dayExt;
document.write(extDate + "Today is the day of ");
document.write(monthName[today.getMonth()] + " in the year ");
document.write(myYear + ".");
// -->
</script>
当前结果:无
预期结果:今天是2019年3月31日的星期日。
答案 0 :(得分:1)
这是解决问题的一种方法。任务本身很简单-请注意
${expression_goes_here}
document.write
仍然给我们许多噩梦!
"use strict";
window.addEventListener('load', function()
{
var monthNames = ['January','Febuary','March','April','May','June','July','August','September','October','November','December'];
var dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var today = new Date();
var dayName = dayNames[today.getDay()];
var monthName = monthNames[today.getMonth()];
var dayOfMonth = today.getDate();
var ext = dayOfMonth % 10; // extract last (least significant) digit
switch (ext)
{
case 1: ext = "st"; break;
case 2: ext = "nd"; break;
case 3: ext = "rd"; break;
default: ext = "th"; break;
}
var text = `Today is ${dayName}, the ${today.getDate()}${ext} day of ${monthName} in the year ${today.getFullYear()}`;
var textElem = document.createTextNode(text);
document.body.appendChild(textElem);
}, false );
switch
语句。${}
来划分变量等,document.write
总是习惯(我也不想检查!)有点粗糙,因为在页面中的第一次使用会核对并删除已经发送到浏览器的所有内容(脚本,样式等等。)一个更好的解决方案是创建一个具有一定描述性的HTML元素,在将该元素添加到页面之前设置该元素的内容。我使用了一个text-node,它模糊地相当于“ no-element”-文本不会被尖括号和html标签包围。这是表格:
window.addEventListener('load', callThisFuncWhenLoadEventReceived, false);
我可以指定响应此事件而要调用的函数的名称,或者我可以像在此所做的那样使用不带名称的函数(匿名函数)