当我只想显示时间时脚本打印未定义

时间:2017-11-22 06:04:44

标签: javascript html

所以这是我的剧本

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>

但是当网页加载时,在显示的第一秒时,它会在undefined之类的时间字符串末尾始终显示12:12undefined

1 个答案:

答案 0 :(得分: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>