在特定的html标记中使用JavaScript显示日期

时间:2012-03-15 19:29:40

标签: javascript html

我有这个简单的Java Script代码来显示日期。 我想从js中获取结果,并在文档中的特定html中显示它们。例; div,p,h3等 如果我将脚本放在标记中,它将覆盖我现有的html页面。 如何在html页面中的特定标签中显示日期?

<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>

2 个答案:

答案 0 :(得分:3)

由于您提到的原因,您几乎从不使用document.write。也就是说,如果在页面完成渲染后应用,它将覆盖现有页面。

只是做

document.getElementById('id-of-element-to-write-into').innerHTML = 
    month_names[current_date.getMonth()] +
    " " + current_date.getDate() +
    " " + current_date.getFullYear()

您也可以使用

代替document.getElementById

或只是

答案 1 :(得分:1)

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

http://jsfiddle.net/22MVm/1/