2016-02-29 24 views
-3

我想成立時間對網頁進行自動去,所以我有id屬性的html代碼:如何在自己的html網頁上設置時間功能?

<div id="demo"> 

</div> 

和JS的功能,這使得時間用戶:

function tellTime() { 
var now = new Date(); 
var theHr = now.getHours(); 
var theMin = now.getMinutes(); 
document.write("time: " + theHr + ":" + theMin); 
} 
document.getElementById("demo").innerHTML = tellTime(); 

所以當頁面重新加載它似乎時間但用戶muss重新加載頁面,以查看當前時間。

我們怎樣才能設置Function,它不需要重新加載看什麼是當前時間?

感謝

回答

0
<!DOCTYPE html> 
<html> 
<body> 

<p>A script on this page starts this clock:</p> 

<p id="demo"></p> 

<button onclick="clearInterval(myVar)">Stop time</button> 

<script> 
var myVar = setInterval(myTimer ,1000); 
function myTimer() { 
    var d = new Date(); 
    document.getElementById("demo").innerHTML = d.toLocaleTimeString(); 
} 
</script> 

</body> 
</html> 

http://www.w3schools.com/js/tryit.asp?filename=tryjs_setinterval3

+0

避免鏈接到W3Schools的。鏈接到質量更好的在線資源(如MDN或W3)要好得多。 – BenM

0

使用setInterval()

function tellTime() 
{ 
    var now = new Date(), 
     hrs = now.getHours(), 
     min = now.getMinutes(), 
     sec = now.getSeconds(); 

    document.getElementById("demo").innerHTML = ("time: " + hrs + ":" + min + ':' + sec); 
} 

window.setInterval(tellTime, 1000); 

jsFiddle Demo

0

您可以用setTimeout自動刷新,或使一個事件(單擊事件例如)重新加載的時候,用的setTimeout可以使時間每秒刷新一次,這樣的:

function tellTime() { 
    var now = new Date(); 
    var theHr = now.getHours(); 
    var theMin = now.getMinutes(); 
    return "time: " + theHr + ":" + theMin; 
} 

function printTime() { 
    document.getElementById("demo").innerHTML = tellTime(); 
    setTimeout(printTime, 1000); // Run this function again after a second 
} 
0

你需要使用setInterval

function tellTime() { 
 
    var now = new Date(); 
 
    var theHr = now.getHours(); 
 
    var theMin = now.getMinutes(); 
 
    var theSec = now.getSeconds(); 
 
    return "time: " + theHr + ":" + theMin + ":" + theSec; 
 
} 
 
setInterval(function() { 
 
    document.getElementById("demo").innerHTML = tellTime(); 
 
}, 1000);
<div id="demo"> 
 
</div>