Javascript 如何获取本地存储值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11247235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the local Storage Value
提问by srinu
var cookieValue = document.getElementById("demo");
var value = cookieValue .getAttribute('value');
if(typeof(Storage)!=="undefined")
{
alert(value);
localStorage.setItem = ("GetData" , value);
alert(localStorage.setItem);
}
function loading()
{
alert("coming");
var allcookies = localStorage.getItem('GetData');
alert(allcookies);
}
Above is the way I am setting localStorage.setItemand I am getting LocalStorage.
But Where I didn't get the output it is showing Null. Please Suggest me any Solution.
以上是我设置localStorage.setItem和获取 LocalStorage 的方式。但是在我没有得到输出的地方,它显示的是 Null。请建议我任何解决方案。
回答by Jerome Cance
Your code should be :
你的代码应该是:
var cookieValue = document.getElementById("demo");
var value = cookieValue .getAttribute('value');
if(typeof(Storage)!=="undefined")
{
alert(value);
localStorage.setItem("GetData" , value);
alert(localStorage.getItem("GetData"));
}
function loading()
{
alert("coming");
var allcookies = localStorage.getItem('GetData');
alert(allcookies);
}
OR
或者
var cookieValue = document.getElementById("demo");
var value = cookieValue .getAttribute('value');
if(typeof(Storage)!=="undefined")
{
alert(value);
localStorage["GetData"] = value;
alert(localStorage["GetData"]);
}
function loading()
{
alert("coming");
var allcookies = localStorage["GetData"];
alert(allcookies);
}
回答by Brant Olsen
The correct syntax for setItemis
正确的语法setItem是
localStorage.setItem("GetData", value)
localStorage.setItem("GetData", value)
not
不是
localStorage.setItem = ("GetData", value)
localStorage.setItem = ("GetData", value)
回答by Esailija
Try this
尝试这个
if( window.localStorage ) {
alert(value);
localStorage.setItem("GetData" , value);
}

