简体   繁体   中英

How can I show the time (generated by JavaScript) in a specific div?

While learning JavaScript, I found the following code:

function printTime() {
  var d = new Date();
  var hours = d.getHours();
  var mins = d.getMinutes();
  var secs = d.getSeconds();
  document.body.innerHTML = hours+":"+mins+":"+secs;
}

setInterval(printTime, 1000);

In Codepen this does not show anything while the HTML and CSS sections are empty. The main question is: how can I insert the generated time on a specific place in the HTML document?

For example, the time should be placed in this div:

<div id="time" class="main__section--time">
    /* show time here */
</div>

How can I link this function to an ID or class to show the output in this div?

You have to modify your printTime function like this:

function printTime() {
  var d = new Date();
  var hours = d.getHours();
  var mins = d.getMinutes();
  var secs = d.getSeconds();
  // select the div by its id
  document.getElementById("time").innerHTML = hours+":"+mins+":"+secs;
}

Try it in the snippet below:

 function printTime() { var d = new Date(); var hours = d.getHours(); var mins = d.getMinutes(); var secs = d.getSeconds(); document.getElementById("time").innerHTML = hours+":"+mins+":"+secs; } setInterval(printTime, 1000); 
 <div id="time" class="main__section--time"> </div> 

而不是document.body.innerHTML你只需使用document.getElementById("time").innerHTML

You can use the document.querySelector API together with a CSS selector to reference a specific element on the page.

 var timeDisplayElement = document.querySelector('#my-time'); function printTime() { var d = new Date(); var hours = d.getHours(); var mins = d.getMinutes(); var secs = d.getSeconds(); timeDisplayElement.innerHTML = hours+":"+mins+":"+secs; } setInterval(printTime, 1000); 
 <div id="my-time"></div> 

使用document.getElementById("time").innerHTML = ...

You need to specify the div's id with

document.getElementById ("time")

And then access to it's innerHTML property

function printTime() { 
     var d = new Date(); 
     var hours = d.getHours(); 
     var mins = d.getMinutes(); 
     var secs = d.getSeconds();
     document.body.innerHTML= hours+":"+mins+":"+secs;
}  
 setInterval(printTime, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM