2017-04-25 44 views
0

由于标题可能会放弃,我正试图跨页刷新增加分数值。我不完全确定我的设置是否正确,因此有点评论。不寻找直接的答案,只是一些指针和建议,以达到我需要的地方。在jquery中增加和存储变种

var score = 0; 
//localStorage.setItem("score", score); 
var rounds; 
var ans; 
var img; 
img = document.getElementsByClassName("image")[0].id; 
$(".answer").click(function() { 
ans = $(this).attr('id'); 
if (ans === img) { 
    //score++; 
    //score = localStorage.getItem("score", score); 
    score++; 
    //localStorage.setItem("score", score); 
    //rounds++; 
    alert('right answer'); 
    location.reload(); 
} else { 
    //score = 0; 
    //rounds++; 
    alert('wrong answer'); 
    //location.reload(); 
} 
}); 
//var res = localStorage.getItem("score", score) 
//console.log(res); 

一直在玩查询几天,所以仍然盲目地感觉。任何帮助都会很棒。其余的脚本可以在这里找到jfiddle

+1

要坚持这一点对页面刷新,你既可以将代码存储在后端,并在以后的时间把它或将它储存在浏览器中(即饼干)。我推荐后者。 – henry

+1

如果你想跨页面加载而不使用数据库/写入文件来存储一个值,你将需要了解创建/读取cookies –

+2

正如@harrison所说,你需要将它存储在某个地方,因为JS中的变量无法在页面中生存刷新。你的'localStorage'代码有一些代码。那有什么问题? –

回答

2

我觉得你是在正确的轨道上使用localStorage。这很容易掌握,并且您已经开始实施一些代码。你想要做的第一件事是通过调用localStorage.getItem('score');初始化分数变量。 getItem没有第二个参数。

那么你需要决定应该在增加之前还是之后保存分数?根据这个问题的答案,你会打电话localStorage.setItem('score', score);

https://developer.mozilla.org/en-US/docs/Web/API/Storage