jQ: Parse localstorage & stringify values

只愿长相守 提交于 2020-01-05 07:07:20

问题


I am storing some values in localStorage using stringify and I'm trying to parse them but it doesn't work for me.

This is how I add the values:

localStorage.setItem('a', JSON.stringify({ userid : '4361', value : '23' }));

And this is how I parse them:

$('p').text(JSON.parse(localStorage.getItem('a')));

Here is the fiddle: http://jsfiddle.net/hrHfG/

Also, I'd like to know how can I parse each value separately. For example, only the userid of 'a', or only the value, if its possible.

Thanks a lot


回答1:


That is because JSON.parse(localStorage.getItem('a')) returns an object. You cannot use an object like that as an argument in .text().

This works though:

$('p').text(JSON.parse(localStorage.getItem('a')).value);


来源:https://stackoverflow.com/questions/8079380/jq-parse-localstorage-stringify-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!