简体   繁体   中英

innerHTML = Date() working in fiddle, but not in Chrome or IE

So I decided to just randomly make an updating time and date element using JavaScript and HTML. The code is below:

HTML

<!DOCTYPE html>
<html>
<head>
<script src="timer.js"></script>
</head>
   <body>
    <span id="time"></span>
   </body>
</html>

JavaScript(timer.js)

var e = document.getElementById("time");
window.onload = setInterval(
    function () { 
       e.innerHTML = Date();
},
    1000);

It works in this JSFiddle , but does not work when I load the HTML with Google Chrome and especially not with IE. Does anyone know why that is? This is more of a question of curiosity rather than a coding issue. Thank you for the feedback!

setInterval does not return a function. It returns an ID you can use to cancel it later. The getElementById is also outside of it, so that will just return null because the element isn't loaded yet when it's trying to get it. Fixed code:

window.onload = function() {
    var e = document.getElementById("time");
    setInterval(function() { 
       e.innerHTML = Date();
    }, 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