我的javascript时钟不会显示时间

时间:2015-11-16 02:32:25

标签: javascript clock

我对javascript相对较新,我尝试编写一个只有时钟显示的简单网页,以便彻底了解该语言。我不确定为什么时钟不会出现在盒子里。谁能指出我正确的方向?我的代码如下。

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>A Simple Clock</title>
</head>

<body>
   <h1>
      A Simple JavaScript Clock
   </h1> 
   <form action="">
      <p><input type="text" id="time" /></p>
   </form>
   <script>
        "use strict";
        var tick =  setInterval("digitalClock()", 1000);

        function digitalClock() {

        var currentTime = new Date();

        var hours = currentTime.getHours();
        var minutes = currentTime.getMinutes();
        var seconds = currentTime.getSeconds();

        if (minutes < 10) {
        minutes = "0" + minutes;
        }
        if (seconds < 10) {
        seconds = "0" + seconds;
        }

        currentTime = hours + ':' + minutes + ':' + seconds;
        currentTime = document.getElementById("time");

       }

       window.onload = digitalClock();
       </script>
</body>
</html>

提前致谢。

2 个答案:

答案 0 :(得分:0)

更改这两行:

  

currentTime =小时+':'+分钟+':'+秒;     currentTime = document.getElementById(“time”);

与此类似:

// Creates a string which can be displayed in the box
var currentTimeStr = hours + ':' + minutes + ':' + seconds;
// Sets the value of the 'time' input to the time string
document.getElementById("time").value = currentTimeStr;

答案 1 :(得分:0)

这是您的工作代码,您可以在加载页面时设置函数start execute。无需在带有大括号的setInterval函数内引用。您可以使用其value属性为输入赋值。

        "use strict";

        function digitalClock() {

          var currentTime = new Date();

          var hours = currentTime.getHours();
          var minutes = currentTime.getMinutes();
          var seconds = currentTime.getSeconds();

          if (minutes < 10) {
            minutes = "0" + minutes;
          }
          if (seconds < 10) {
            seconds = "0" + seconds;
          }

          currentTime = hours + ':' + minutes + ':' + seconds;
          document.getElementById("time").value = currentTime;

        }

        window.onload = function() {
          setInterval(digitalClock, 1000);
        };
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>A Simple Clock</title>
</head>

<body>
  <h1>
      A Simple JavaScript Clock
   </h1> 
  <form action="">
    <p>
      <input type="text" id="time" />
    </p>
  </form>
</body>

</html>