我注意到您的代码存在其他一些问题,我已经评论了修复并添加了一些其他提示。
var seconds = 0;
var clockId;
var correctAns;
// Lets get a reference to the quizclock element and save it in
// a variable named quizclock
var quizclock = document.getElementById('quizclock');
function runClock() {
// seconds + 1;
// This calculates seconds + 1 and then throws it away,
// you need to save it back in to the variable
// You could do that with:
// seconds = seconds + 1;
// But it would be even better with the shorthand:
seconds += 1;
// set the HTML inside of the quizclock element to new time
quizclock.innerHTML = seconds;
}
function startClock() {
showQuiz();
runClock();
// setInterval("runClock()", 1000);
// When using setInterval and setTimeout you generally just
// want to directly pass it the function by name. Passing it
// a string "runClock()" is in effect actually running
// eval("runClock()"), eval should be avoided unless you
// really need it.
// setInterval returns a number which identifies the interval,
// you need to save that number, you'll need it when you
// call clearInterval
clockId = setInterval(runClock, 1000);
}
function stopClock() {
// clearInterval takes the id that setInterval
// returned to clear the interval
clearInterval(clockId);
gradeQuiz();
// you had this alert statment after the return statement,
// it would have never run, return statements end the
// function and anything after them is ignored
alert("You have " + correctAns + " correct out of 5 in " +
quizclock + " seconds.");
//return = correctAns;
// the return statement doesn't need a =,
// return = correctAns says set a variable named return to the
// value of correctAns since return is a reserved word,
// that should generate an error
return correctAns;
}
一些有用的参考链接:
如果这是一个正式的类,你可能只需要使用基本的 DOM 方法来获取元素(getElementById
等)。如果您只是自学,我会鼓励您学习 DOM 库。我建议jQuery,它很容易学习,现在或多或少是事实上的标准。使用 jQuery 而不是document.getElementById('quizclock')
你可以这样做:$('#quizclock')
. 使用 jQuery 可以使您的代码更短,标准化不同浏览器之间的内容,并帮助保护您免受这些浏览器中的错误的影响。
你现在只是一个初学者,在像这样的小例子中你不需要担心全局变量,但你应该知道使用太多它们通常是一个坏主意。如果页面上的另一个函数也使用了一个名为 的全局变量seconds
怎么办?它可能会改变seconds
并搞砸你的计时器。这有点进步,但避免这种情况的一种方法是将代码包装在自调用匿名函数中:
(function () {
var seconds = 0;
// inside here seconds is visible and can be used
}());
// outside seconds is not declared, it will return undefined.
不幸的是,内部的任何功能在外部也不可见,因此通过附加它们onclick=
不起作用,但您可以(应该)使用 DOM 附加它们:
var submitButton = document.getElementById('submitanswers'); // you'll have to give the button an id
submitButton.addEventListener('click', stopClock, false);
同样,使用 jQuery 会使这更容易:
$('#submitanswers').on('click', stopClock);
同样,如果您使用 jQuery,它已经迫使您将代码包装在一个函数中,这将使您的变量远离全局命名空间:
$(document).ready(function () {
var seconds;
// again seconds is visible here
});
// but not here