从本地存储 jquery 检索对象



我正在尝试使用 jquery 将对象存储在本地存储中,但似乎无法得到不同的结果:[对象对象]。

例如,我如何在下面的代码中控制台登录国家/地区?

<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
</head> 

<input type="text" id="text"> 
<button value="save" onClick="setStorage()" id="btn"> Save </button>

<script>
function setStorage(){
var text = $("#text").val();
testobj = {'country' : 'testcountry', 'population' : 3}
localStorage.setItem('storage', {'text' : testobj});
var retreived = localStorage.getItem('storage');
console.log('retreived : '  + retreived);
}
</script>

localStorage存储字符串。出于这个原因,我在将对象等写入存储时存储 JSON,在存储时使用JSON.stringify,在检索时使用JSON.parse

function setStorage(){
var text = $("#text").val();
testobj = {'country' : 'testcountry', 'population' : 3}
localStorage.setItem('storage', JSON.stringify({'text' : testobj}));
var retreived = JSON.parse(localStorage.getItem('storage'));
console.log('retreived : '  + retreived);
}

最新更新