秒表不工作

时间:2015-06-29 14:03:44

标签: javascript jquery html stopwatch

我在网上找到了这个秒表教程,但是当我尝试实现它时,它在我检查元素时在控制台中一直说“TypeError:start is null”和“TypeError:h1 is undefined”。更让我烦恼的是,当我在这里插入代码时,它可以工作,如果我把它放入记事本++它不起作用。是否有一个jquery文件,我可能在实现过程中错过了一些,以及一些代码片段是如何使它工作的?

var h1 = document.getElementsByTagName('h1')[0],
    start = document.getElementById('start'),
    stop = document.getElementById('stop'),
    clear = document.getElementById('clear'),
    seconds = 0, minutes = 0, hours = 0,
    t;

function add() {
    seconds++;
    if (seconds >= 60) {
        seconds = 0;
        minutes++;
        if (minutes >= 60) {
            minutes = 0;
            hours++;
        }
    }
    
    h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);

    timer();
}
function timer() {
    t = setTimeout(add, 1000);
}
timer();


/* Start button */
start.onclick = timer;

/* Stop button */
stop.onclick = function() {
    clearTimeout(t);
}

/* Clear button */
clear.onclick = function() {
    h1.textContent = "00:00:00";
    seconds = 0; minutes = 0; hours = 0;
}
<h1><time>00:00:00</time></h1>
<button id="start" >start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>

2 个答案:

答案 0 :(得分:0)

将所有代码(包括函数)包装在一个名为initialize() { }的comon函数中。

然后,在<body>标记上添加功能绑定onload事件,如下所示:

<body onload="initialize()">

除非已经创建了整个DOM和元素,否则这将告诉您的代码不要执行,因为除非它们都已完全加载,否则无法访问它们。

答案 1 :(得分:0)

可能,您已经在HTML之前定义了Javascript。请记住,Javascript是一种阻止语言,因此它将暂停所有操作(包括加载HTML),直到脚本完成。

将脚本移到HTML下方或使用某种形式的$(document)ready