[英]store a var local on a pc with javascript
我试图将本地玩家的高分存储在他的PC上。 我不知道这是否可行,并且在此站点上没有找到关于此的问题。 我只有一个包含数字的变量。 我想将其存储在他的PC上,以便当玩家再次在浏览器中玩游戏时,他的高分仍然可用。
使用本地存储:
window.localStorage.score="20" // storing
window.localStorage.score // getting the score again.
旧的浏览器不支持localStorage
。 因此请使用cookie作为后备。
if(window.localStorage)
window.localStorage.setItem("highscore",1000);
else
document.cookie="highscore=1000; expires=Thu, 31 Dec 2018 12:00:00 UTC";
检索值
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0)
return c.substring(name.length,c.length);
}
return "";
}
if(window.localStorage)
var highscore=window.localStorage.getItem("highscore");
else
var highscore=getCookie("highscore");
除非我们正在谈论将nodeJS(?)存储到文件系统或其他本地存储中,否则这是一件奇怪的事情。
如果您想保留某个值,那么下次加载时将使用javascript上存储的位置进行加载,那么您必须使用Cookie进行操作,但是每次您清除Cookie时都会清除它,并且不会在您计算机上的多个浏览器之间共享。
就是说,这就是您使用javascript将值存储到cookie的方法:
document.cookie =“ somekey = savedValue”;
var readValue = document.cookie;
除了localStorage
之外,您还可以使用Cookies。
var expDate=new Date();
var score=20;
expDate.setDate(expDate.getDate()+365); // expiration after one year
// Setting cookie
document.cookie='score='+score+';expires='+expDate;
// Retrieving the cookie
var yourOldScore = document.cookie.match(/score=(.*?)\;/)[1];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.