【问题标题】:digital current running clock using javascript not working使用javascript的数字当前运行时钟不起作用
【发布时间】:2014-11-02 19:40:44
【问题描述】:
<html>

<body>

<script type="text/javascript" language="javascript">
function renderTime () {

var currentTime = new Date();
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();

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


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


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

myClock.textContent = h + ":" + m + ":" + s;
myClock.intterText = h + ":" + m + ":" + s;


setTimeout ('renderTime()',1000);


}
renderTime();
</script>

</body>
</html>

这是我的代码,我正在尝试让当前正在运行的数字 24 小时时钟运行,我遵循代码并搜索了所有地方,但我的代码不起作用? 我做错了什么?

【问题讨论】:

  • myClock 似乎未定义。
  • 你的意思可能是innerText,而不是intterText

标签: javascript time styles clock


【解决方案1】:

正如人们在 cmets 中提到的那样,您的代码存在一些问题。 首先,你拼错了innerText。 其次,myclock 未定义。我假设你的意思是它是一个&lt;p&gt; 标签。 正如@printr 提到的,您应该使用setInterval。 但这里是工作代码,你的修改很少:

<html>
    <body>
        <p id="clock"></p>
    <script type="text/javascript" language="javascript">
        var myClock = document.getElementById("clock");
        function renderTime () {
            var currentTime = new Date();
            var h = currentTime.getHours();
            var m = currentTime.getMinutes();
            var s = currentTime.getSeconds();

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


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


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

            //myClock.textContent = h + ":" + m + ":" + s;
            myClock.innerText = h + ":" + m + ":" + s;

            setTimeout(renderTime, 1000);
        }
        renderTime();
    </script>
</body>

【讨论】:

    【解决方案2】:

    您的代码有几个问题。 JavaScript 不会为您纠正拼写错误!如上所述,您需要使用innerText,而不是intterText

    您的 renderTime() 函数已打开,但未关闭,这将引发“输入意外结束”错误(检查您的开发者控制台)。

    另外:您需要使用 setInterval(),而不是 setTimeout()。 setInterval() 将根据指定的时间间隔运行一个函数,以毫秒为单位。 1000 毫秒 = 1 秒。所以,看起来像这样:

    setInterval(function(){
        // Code to run ...
    }, 1000);
    

    这是一个有效的 JSFiddle:
    http://jsfiddle.net/zc44tuea/

    【讨论】:

    • 我会修改 12 以获得正确的时间,而不是使用 mil 时间。
    • 如果这是一个专业时钟,我也会使用更小的超时,所以它并不总是关闭 0-1 秒。
    • 如果这是一个专业的时钟,我们可能会做各种不同的事情......
    猜你喜欢
    • 2021-02-12
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多