2012-03-15 39 views
0

我有這個簡單的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> 
+1

申請宣告該陣列不必盡一切month_mans.length混亂。您可以簡單地做 var month_names = [「January」,「February」,「March」,「April」,「May」,「June」,「July」,「August」,「September」,「October」 ,「十一月」,「十二月」];' 並且您將得到完全相同的結果 – webdesserts 2012-03-15 19:35:04

回答

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/

+0

我認爲您的解決方案對於初學者來說更容易理解,而不是僅僅交出代碼,爲什麼你做了一些你做過的事情,可能會增加一些評論? – webdesserts 2012-03-15 19:50:32

+0

@mcmullins感謝您對我的回覆提示。我已經更新了上面的代碼,但只留下了小提琴。 – slowBear 2012-03-15 19:54:23

+0

作爲一個初學者,我覺得這是一個小eaiser要了解,我仍然有一個問題讓日期出現在我的html頁面。我不知道爲什麼它不會在我創建的日期div id中執行。 – user1272441 2012-03-21 23:50:15

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,你也可以使用

或者只是

+0

當您應該使用document.write()時,有絕佳的時機。 – j08691 2012-03-15 19:36:40

+0

@ j08961請詳細說明,在這種情況下,您應該使用'document.write'而不是DOM操作?它違背了JS和HTML之間的分離,除非將腳本標記放置在文檔的特定部分,否則它會使您的功能無法使用。從來沒有聽說過任何人支持document.write – 2012-03-15 19:38:44

+0

有一種情況是可選地在html中包含腳本,具體取決於在線副本的存在......例如:如果聯機副本無法訪問,則僅包含jQuery的本地副本。在h5bp模板[here](https://github.com/h5bp/html5-boilerplate/blob/master/index.html#L51)中可以看到這個使用的例子。 – webdesserts 2012-03-15 19:40:43

相關問題