在特定的html标记中显示与JavaScript的日期
我有这个简单的Java脚本代码来显示日期。 我想从js中获取结果,并在文档中的特定html中显示它们。例; div,p,h3等 如果我把脚本放在标签中,它会覆盖我现有的html页面。 如何在html页面中的特定标签中显示日期?在特定的html标记中显示与JavaScript的日期
<script language="JavaScript">
<!--
var current_date = new Date ();
var month_names = new Array ();
month_names[month_names.length] = "January";
month_names[month_names.length] = "February";
month_names[month_names.length] = "March";
month_names[month_names.length] = "April";
month_names[month_names.length] = "May";
month_names[month_names.length] = "June";
month_names[month_names.length] = "July";
month_names[month_names.length] = "August";
month_names[month_names.length] = "September";
month_names[month_names.length] = "October";
month_names[month_names.length] = "November";
month_names[month_names.length] = "December";
document.write (month_names[current_date.getMonth()]);
document.write (" " + current_date.getDate());
document.write (" ");
document.write (" " + current_date.getFullYear());
// -->
</script>
var months = [ //create the months
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
], d, m, y, now, out_string; //vars to hold date, month, year, date object and output string
now = new Date(); //new date object
d = now.getDate(); //current date
m = now.getMonth(); // current month
y = now.getFullYear(); //current year
out_string = months[m] + ' ' + d + ' , ' + y; //concat date parts into output string
document.getElementById('yourIDHere').innerHTML = out_string; //set the html of the hmtl element to the output string
我认为您的解决方案对于初学者来说更容易理解,而不是仅仅交出代码,为什么你做了一些你做过的事情,可能会增加一些评论? – webdesserts 2012-03-15 19:50:32
@mcmullins感谢您对我的回复提示。我已经更新了上面的代码,但只留下了小提琴。 – slowBear 2012-03-15 19:54:23
作为一个初学者,我觉得这是一个小eaiser要了解,我仍然有一个问题让日期出现在我的html页面。我不知道为什么它不会在我创建的日期div id中执行。 – user1272441 2012-03-21 23:50:15
你几乎从来没有用你提到的原因使用document.write
。也就是说,如果在页面完成渲染后应用,它将覆盖现有页面。
只是做
document.getElementById('id-of-element-to-write-into').innerHTML =
month_names[current_date.getMonth()] +
" " + current_date.getDate() +
" " + current_date.getFullYear()
相反的document.getElementById
,你也可以使用
- https://developer.mozilla.org/en/DOM/document.getElementsByTagName(最安全的跨浏览器)
- https://developer.mozilla.org/en/DOM/document.querySelector
- https://developer.mozilla.org/en/DOM/document.getElementsByClassName
或者只是
当您应该使用document.write()时,有绝佳的时机。 – j08691 2012-03-15 19:36:40
@ j08961请详细说明,在这种情况下,您应该使用'document.write'而不是DOM操作?它违背了JS和HTML之间的分离,除非将脚本标记放置在文档的特定部分,否则它会使您的功能无法使用。从来没有听说过任何人支持document.write – 2012-03-15 19:38:44
有一种情况是可选地在html中包含脚本,具体取决于在线副本的存在......例如:如果联机副本无法访问,则仅包含jQuery的本地副本。在h5bp模板[here](https://github.com/h5bp/html5-boilerplate/blob/master/index.html#L51)中可以看到这个使用的例子。 – webdesserts 2012-03-15 19:40:43
申请宣告该阵列不必尽一切month_mans.length混乱。您可以简单地做 var month_names = [“January”,“February”,“March”,“April”,“May”,“June”,“July”,“August”,“September”,“October” ,“十一月”,“十二月”];' 并且您将得到完全相同的结果 – webdesserts 2012-03-15 19:35:04