Javascript高分计数器不更新

时间:2014-01-04 19:08:25

标签: javascript html html5 forms

我正在尝试制作一款测量你的反应时间的游戏,但我的最快得分跟踪器非常多。它在第一次反应测试期间有效但在此之后停止工作。提前感谢任何可以提供帮助的人。

<!DOCTPYE html>
<html>
<head>
<script>

window.onload = alert("Press START to start the game. As soon as the screen turns red click the stop button. Get the fastest time you can. Good luck");
var button = document.getElementById("reactionTester");
var start = document.getElementById("start");
var startTime;
var scoreContainer = document.getElementById("p");
var css = document.createElement("style");
css.type= "text/css";
var counter = 0;
var timer = null;
var highscore = document.getElementById("highscore");
var currentRecord = 0;
var highscoreCounter = 0;
function init(){
var startInterval/*in milliseconds*/ = Math.floor(Math.random()*10)*1000;
clearTimeout(timer);
timer = setTimeout(startTimer,1/*startInterval*/);
document.body.appendChild(css);
css.innerHTML = "html{background-color: blue;}";
}
function startTimer(){

startTime = Date.now();
css.innerHTML="null";
css.innerHTML = "html{background-color: red;}";
if(counter==1){
p1 = document.getElementsByTagName('p')[1];
p1.parentNode.removeChild(p1);
counter++;
}
}

function stopTimer(){
if(startTime){
var stopTime = Date.now();
var dif = stopTime - startTime;
alert("Your time is " + dif + " ms");
startTime = null;
css.innerHTML = null;
var p = document.createElement("p");
document.body.appendChild(p);
p.innerHTML = dif;
counter=1;
if (highscoreCounter != 0){
    if(dif < currentRecord){
        Phighscore2 = document.getElementsByTagName('p')[0];
        Phighscore2.parentNode.removeChild(Phighscore2);
        document.getElementById("highscore").appendChild(highscoreP);
        currentRecord = dif;
        highscoreP.innerHTML = currentRecord;
    }
    else{}
}
else{
    var highscoreP = document.createElement("p");
    document.getElementById("highscore").appendChild(highscoreP);
    currentRecord = dif;
    highscoreP.innerHTML = currentRecord;
    highscoreCounter++;
}
}
else{
alert("don't trick me");
}
}

</script>
</head>
<body>
<div id="highscore">

</div>
<form id="form">
<div class="tableRow">
<input type="button" value="start" id="start" onclick="init()">
</div>
<div class="tableRow">
<input type="button" id="reactionTester" onclick="stopTimer()" value="stop">
</div>
<div id="p">
</div>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您的问题是由highscoreP本地定义变量function stopTimer引起的。局部变量在函数返回时失去其值。使它成为一个全局变量(并且不要忘记在函数中删除它的'var'关键字。)

我无法拒绝对您的代码做一些额外的评论:

  • 不要一遍又一遍地创建相同的DOM元素;它使您的代码复杂化并强调浏览器的内存管理器。静态定义所有元素,并按照ID对您的容器进行引用(highscore,p)。
  • 不要动态构建 style 元素,这是非常糟糕的做法。相反,静态定义CSS类,然后通过设置属性className动态分配类。
  • 即使你在普通的javascript编程方面做得很好,你也可以考虑使用jQuery。