1

我在我的代码中遇到了一个障碍,下面的代码是一个完美运行的 JavaScript 时钟:

function renderTime() {
    var currentTime = new Date();
    var diem = "AM";
    var h = currentTime.getHours();
    var m = currentTime.getMinutes();
    var s = currentTime.getSeconds();

    if(h == 0) {
        h = 12;
    } else if(h > 12) {
        h = h - 12;
        diem = "PM";
    }
    if(h < 10) {
        h = "0" + h;
    }
    if(m < 10) {
        m = "0" + m;
    }
    if(s < 10) {
        s = "0" + s;
    }
    var myClock = document.getElementById('clockDisplay');
    myClock.textContent = h + ":" + m + ":" + s + " " + diem;
    myClock.innerHTML = h + ":" + m + ":" + s + " " + diem;
    myClock.innerText = h + ":" + m + ":" + s + " " + diem;
    setTimeout('renderTime()',1000);

}
renderTime();

但是,我现在尝试这样做略有不同:

function makeTime() {
    var currentTime = new Date();
    var diem = "AM";
    var h = currentTime.getHours();
    var m = currentTime.getMinutes();
    var s = currentTime.getSeconds();

    if(h == 0) {
        h = 12;
    } else if(h > 12) {
        h = h - 12;
        diem = "PM";
    }
    if(h < 10) {
        h = "0" + h;
    }
    if(m < 10) {
        m = "0" + m;
    }
    if(s < 10) {
        s = "0" + s;
    }
    var clock = document.getElementById('clock');
    clock.innerHTML = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
    myClock.textContent = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
    myClock.innerText = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
    setTimeout('makeTime()',1000);
}
makeTime();

这个有效,但是不像另一个那样更新,您必须手动刷新页面。

我究竟做错了什么?

4

1 回答 1

3

myClock当您将变量重命名为时,您继续在第二个版本中引用clock

var clock = ...
clock.innerHtml = ...
myClock.textContent = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
myClock.innerText = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
setTimeout('makeTime()',1000);

这会导致错误 ( reference error: myClock is not defined),从而阻止执行流程到达您的setTimeout调用。

您应该学习使用可用的工具。每个浏览器都有一种向开发人员报告 JavaScript 错误的方法。在 Webkit/IE10 中打开开发者控制台,或在 Firefox 中打开 Firebug,您将看到这些错误以及它们在代码中发生的确切位置。

于 2013-09-24T18:04:34.673 回答