简体   繁体   中英

JavaScript clock reloads to its own page?

I am trying to add a clock to my website with JavaScript, but I have a problem. The HTML page with my script in it will load and display everything in HTML, but about 1 second later will reload and only display the output of the JavaScript (only display the clock).

Here is my code:

window.onload = setInterval(clock, 1000);
var time = document.getElementById('TIME');

function clock() {
  var date = new Date();
  var localtime = date.toString();
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  document.open("text/html", "replace");
  document.write("Time: " + hours + ":" + minutes + ":" + seconds);
}

It would go from this: Displays everything in HTML file

To displaying JUST THIS: "Time: 15:16:56"

I have no idea what I did wrong and it would be awesome if I can get some help. (I am just learning how to use JavaScript)

 window.onload = setInterval(clock, 1000); var time = document.getElementById('TIME'); function clock() { var date = new Date(); var localtime = date.toString(); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); time.innerHTML = "Time: " + hours + ":" + minutes + ":" + seconds; }
 <div id="TIME"></div>

It's because you're using document.open(...) . That reloads the page.

You should just do this:

time.innerHTML = "Time: " + hours + ":" + minutes + ":" + seconds;

instead of

document.open("text/html", "replace");
document.write("Time: " + hours + ":" + minutes + ":" + seconds);

UPDATE:

I just saw I made a typo. This code works (on codepen):

 window.onload = setInterval(clock, 1000); var time = document.getElementById('TIME'); function clock() { var date = new Date(); var localtime = date.toString(); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); time.innerHTML = "Time: " + hours + ":" + minutes + ":" + seconds; }
 <div id="TIME"></div>

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