将变量存储在HTML5 localStorage中 [英] Storing variables in HTML5 localStorage

查看:147
本文介绍了将变量存储在HTML5 localStorage中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个扫雷游戏,我希望在游戏获胜后将' noWins '变量的值存储到本地存储中(我有一个名为 wonGame 的布尔值,当游戏胜出时它被设置为true)。



如何才能做到这点? localStorage,您可以使用 setItem()函数。这个函数接受两个参数,item键和一个值。

  if(wonGame == true){
localStorage .setItem('noWins','value');

$ / code>

在回应您的评论时,

本地存储将值存储为字符串,因此必须使用parseInt将该值转换为数字。 noWins的第一个值将被设置为0,所以新的代码应该是

     code> //设置noWins的初始值为0 
localStorage.setItem('noWins',0)
if(wonGame === true){
var winning = parseInt (localstorage.getItem(noWins);
//递增值
localStorage.setItem(获胜,获胜++)
}
pre>

请注意,胜利只是我创建的变量


I'm currently in development of a minesweeper game and I want to store the value of a 'noWins' variable into local storage once the game is won (I have a boolean called wonGame which is set to true when the game is won).

How can I do this?

解决方案

To store data in localStorage, you use the setItem() function. This function takes two parameters, the item key and a value.

if(wonGame == true){
  localStorage.setItem('noWins', 'value');
}

In response to your comment,

local storage stores values as strings, therefore the value has to be converted to a number using parseInt. The first value for noWins would be set to 0

so the new code should be

//set the initial value of noWins to 0
localStorage.setItem('noWins' , 0)
if (wonGame === true){
var winning = parseInt(localstorage.getItem("noWins");
//increment value
localStorage.setItem("winning", winning++)
}

Note that "winning" is just a variable I created

这篇关于将变量存储在HTML5 localStorage中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆