2017-11-22 2 views
0

は、だからここに私のスクリプト スクリプトが未定義印刷し

function updateClock() { 
 
    var now = new Date(); // current date 
 
    var time = now.getHours() + ':' + now.getMinutes(); // again, you get the idea 
 
    // a cleaner way than string concatenation 
 
    // set the content of the element with the ID time to the formatted string 
 
    document.getElementById('nav-time').innerHTML = time; 
 
    // call this function again in 1000ms 
 
    setTimeout(updateClock, 1000); 
 
}
<li><span id="nav-time">Time 
 
<script>document.write(updateClock());</script></span></li> 
 
<span class="divider"> | </span>
ですが、Webページのロードが、第一、第二のためにそれが表示されるときには常に、 undefinedを持っています 12:12undefinedのような時間文字列の終わり。

+0

あなただけが1秒よりもここにはるかに長い間隔を使用することができます分をしたい場合。 –

答えて

1

document.writeで機能を呼び出す必要はありません。あなたはあなたのページにスクリプトを追加することができます。 setInterval(毎秒の時間を表示したい、setTimeoutではない)を関数自体の外に呼び出す。また、document.getElementById経由で要素にアクセスし、パフォーマンスを向上させる変数に格納します。

const el = document.getElementById('nav-time'); 
 

 
function updateClock() { 
 
    var now = new Date(); 
 
    var time = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds(); 
 
     
 
    el.innerHTML = time;  
 
} 
 

 
setInterval(updateClock, 1000);
<li><span id="nav-time">Time 
 
<span class="divider"> | </span>

+0

おそらく1より長い間隔を使用しますか? –

+0

申し訳ありません。 '000'を忘れてしまった –

関連する問題