从本地存储键获取特定值并填充div。

huangapple go评论77阅读模式
英文:

Get specific value from Localstorage key and populate div

问题

我有一个存储在localStorage中的键,我想获取特定的值并将其填充到一个元素中。

示例:

<div id="results"></div>

document.getElementById('results').innerHTML = localStorage.getItem('customer');

customer = {
    "fullname": "John Doe",
    "firstname": "John"
};

当然,这会输出整个键。我如何检索并显示只有fullname的值?

英文:

I have a key in localStorage and I want to get specific value and populate an element with it.

Example:

&lt;div id=&quot;results&quot;&gt;&lt;/div&gt;

document.getElementById(&#39;results&#39;).innerHTML = localStorage.getItem(&#39;customer&#39;);

customer = {
    &quot;fullname&quot;: &quot;John Doe&quot;,
    &quot;firstname&quot;: &quot;John&quot;
};

This of course outputs the full key. How do I retrieve and display just the value of fullname ?

答案1

得分: 1

你可以使用JSON.parse()来解析字符串值并获取你需要的键:

var customer = JSON.parse(localStorage.getItem('customer'));
var fullname = customer.fullname;
document.getElementById('results').innerHTML = fullname;
英文:

You can use JSON.parse() to parse the string value and get the key you need:

var customer = JSON.parse(localStorage.getItem(&#39;customer&#39;));
var fullname = customer.fullname;
document.getElementById(&#39;results&#39;).innerHTML = fullname;

huangapple
  • 本文由 发表于 2023年6月1日 17:09:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76380329.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定