我的javaScript中有一个总和,但是我想使用localstorage保存答案,但是我不确定该如何处理吗?
我的总和本身是:
var val4 = ((655+(val3*4.35) + (val2*4.7) - (val1*6.8))*1.55)+500;
总和本身是正确的,并带有正确的答案,我只想将答案(Val4)存储在LocalStorage中。
localstorage允许您存储键值对。要将某些东西存储到本地存储中,请使用
window.localStorage.setItem(key,value);
您可以通过
将项目退休localStorage.getItem(key);
LocalStorage是HTML5功能,并非所有浏览器都支持它。在尝试读取或写入之前,您最好检查浏览器是否支持LocalStorage。同样,LocalStorage仅支持键和值的字符串。因此,您必须在写入LocalStorage和string to to int时掩盖整数的字符串。每个浏览器都为本地存储(通常为5 MB)设置了一些预定义的Quita。如果您超过它,则任何写入LocalStorage的尝试都会引起异常。下面的代码处理这些问题。
/*key should be String, value can be any Javascript object */
function writeToLocalStorage(key,value)
{
if(typeof(Storage) == 'undefined')
{
alert("This feature is not supported by the browser you are using currently");
return false;
}
value = JSON.stringify(value); //serializing non-string data types to string
try
{
window.localStorage.setItem(key, value);
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR) {
alert('Local storage Quota exceeded! .Clearing localStorage');
localStorage.clear();
window.localStorage.setItem(key, value); //Try saving the preference again
}
}
return true;
}
function readFromLocalStorage(key)
{
if(typeof(Storage) == 'undefined')
{
//Broswer doesnt support local storage
return false;
}
value = JSON.parse(localStorage.getItem(key));
return value;
}