使用本地存储来记住高分javascript?

时间:2014-10-18 13:17:03

标签: javascript if-statement local-storage

我正在构建一个简单的点击游戏作为练习,但我无法让它记住最高分。这是我的代码:

<html>
<head>
<script type="text/javascript" src="javascript1.js"></script>
<link type= "text/css" rel= "stylesheet" href= "firstcss.css">
</head>
</head>
<body>
<div id= "div1">
<button onclick= "myFunction()"  id= "something">GO
</button>
</div>
<div id= "div2">
<p id= "paragraph">0</p>
</div>
<p id= "don"></p>
<p id= "record"></p>
<p id= "add"></p>
<script>
var cool = 1;
var best= 0;

function myFunction(){
document.getElementById("something").innerHTML= "Keep Tapping";
document.getElementById("paragraph").innerHTML= cool;
cool++;
var parent = document.getElementById("div1");
setTimeout(function(){
var ooo= cool-1;
document.getElementById("don").innerHTML=  cool-1; 
var parent = document.getElementById("div1");
var child = document.getElementById("something");
parent.removeChild(child);
var parent1 = document.getElementById("div2");
var child1 = document.getElementById("paragraph");
parent1.removeChild(child1);
if(ooo > best){
ooo === best;   
localStorage.setItem("hello", best);
document.getElementById("add").innerHTML= localStorage.getItem("hello");
}
else{
document.getElementById("record").innerHTML= "no new record";
}


}, 3000);
}

</script>
</body>
</html>

我认为问题是if语句中的if语句或localStorage可能有人告诉我如何存储最佳分数谢谢。

2 个答案:

答案 0 :(得分:0)

我认为你试图这样做:

if(ooo > best) {
   best = ooo;
   localStorage.setItem("hello", best);  
   .........
}

使用赋值而不是三等于。

我的更改后的代码:

<html>
<head>
<script type="text/javascript" src="javascript1.js"></script>
<link type= "text/css" rel= "stylesheet" href= "firstcss.css">
</head>
</head>
<body>
<div id= "div1">
<button onclick= "myFunction()"  id= "something">GO
</button>
</div>
<div id= "div2">
<p id= "paragraph">0</p>
</div>
<p id= "don"></p>
<p id= "record"></p>
<p id= "add"></p>
<script>
var cool = 1;
var best= 0;

function myFunction(){
document.getElementById("something").innerHTML= "Keep Tapping";
document.getElementById("paragraph").innerHTML= cool;
cool++;
var parent = document.getElementById("div1");
setTimeout(function(){
var ooo= cool-1;
document.getElementById("don").innerHTML=  cool-1; 
var parent = document.getElementById("div1");
var child = document.getElementById("something");
parent.removeChild(child);
var parent1 = document.getElementById("div2");
var child1 = document.getElementById("paragraph");
parent1.removeChild(child1);
if(ooo > best){
best = ooo;   
localStorage.setItem("hello", best);
document.getElementById("add").innerHTML= localStorage.getItem("hello");
}
else{
document.getElementById("record").innerHTML= "no new record";
}


}, 3000);
}

</script>
</body>
</html>

答案 1 :(得分:0)

每次变量best赋值为0 。变量最佳应取决于localstorage变量

用于分配最佳变量的修改代码

if(localStorage.getItem("hello") == null) {
    var best = localStorage.setItem("hello", 0);
}else {
    var best = localStorage.getItem("hello");
}

在下面找到完整的代码......

http://jsfiddle.net/ptfmpedo/1/