簡體   English   中英

使用javascript的數字當前運行時鍾不起作用

[英]digital current running clock using javascript not working

<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小時時鍾運行起來,我已跟蹤代碼並在每個地方搜索,但我的代碼不起作用? 我究竟做錯了什么?

您的代碼有幾個問題。 JavaScript不會為您糾正拼寫錯誤! 如上所述,您需要使用innerText ,而不是intterText

您的renderTime()函數已打開,但未關閉,這將引發“輸入意外結束”錯誤(請檢查開發者控制台)。

另外:您將要使用setInterval()而不是setTimeout()。 setInterval()將基於指定的時間間隔(以毫秒為單位setInterval()運行函數。 1000毫秒= 1秒。 因此,看起來像這樣:

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

這是一個工作的JSFiddle:
http://jsfiddle.net/zc44tuea/

正如人們在注釋中提到的那樣,您的代碼有幾個問題。 首先,您拼寫了innerText 其次, myclock是不確定的。 我假設您的意思是將其作為<p>標記。 如@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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM