2011-09-05 123 views
-2

我正試圖在<p></p>標籤中包含一個實時時鐘。在html中顯示javascript日期

我的js代碼如下:

function updateClock () 
{ 
    var currentTime = new Date (); 

    var currentHours = currentTime.getHours (); 
    var currentMinutes = currentTime.getMinutes (); 
    var currentSeconds = currentTime.getSeconds (); 

    // Pad the minutes and seconds with leading zeros, if required 
    currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes; 
    currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds; 

    // Choose either "AM" or "PM" as appropriate 
    var timeOfDay = (currentHours < 12) ? "AM" : "PM"; 

    // Convert the hours component to 12-hour format if needed 
    currentHours = (currentHours > 12) ? currentHours - 12 : currentHours; 

    // Convert an hours component of "0" to "12" 
    currentHours = (currentHours == 0) ? 12 : currentHours; 

    // Compose the string for display 
    var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay; 

    // Update the time display 
    document.getElementById("clock").firstChild.nodeValue = currentTimeString; 
} 

這是在 「date.js」 文件,該文件我已經包含在HTML代碼

的HTML代碼

<p id="clock">&nbsp;</p> 

但沒有顯示正確的... 任何解決方案?

+5

你的意思是,你複製了一些代碼,並沒有立即開始工作,現在想讓我們爲你調試?我想如果你告訴我們你試過的東西,你得到的是什麼錯誤信息等等,你會更好。 –

+3

你甚至在任何地方調用函數'updateClock()'嗎? –

+0

http://jsfiddle.net/QvuES/至少它可以在Google Chrome和IE9上運行。 1.使用控制檯檢查錯誤2.將'firstChild.nodeValue'改爲'innerText' – JiminP

回答

0

document.getElementById("clock").innerHTML = currentTimeString;應該做的伎倆

1

<p>元件,其ID爲「時鐘」和你的值設置爲

document.getElementById("clock").firstChild.nodeValue = currentTimeString; 

哪裏是子元素(S)爲<p>,它可以在currentTimeString的值設置爲上述HTML文件中不存在或未定義的元素。 。

您都可以,如果你使用的是date.js有功能做你正在做的再建的陳列做的價值像這樣

document.getElementById("clock").innerHTML = currentTimeString; 
0

第一的只是做:

var currentTimeString = new Date().toString('hh:mm:ss tt'); 

您必須確保在運行代碼之前加載了您的頁面。你是否正在運行這個onload onload?或者你是否在頁面末尾調用了你的函數?這些都應該工作。

+0

ref格式說明符http://code.google.com/p/datejs/wiki/FormatSpecifiers – Tommy