gpt4 book ai didi

javascript - 检索本地存储的多个值并在 div 元素中显示

转载 作者:行者123 更新时间:2023-11-28 16:56:43 25 4
gpt4 key购买 nike

我想显示本地存储中所有数据的键及其值。

我写了一些 HTML 和 javascript:

// Setting some values in the local storage
localStorage.setItem("lastname", "Smith");
localStorage.setItem("lastname", "Orange");
localStorage.setItem("lastname", "Green");
localStorage.setItem("lastname", "Pink");


// Attempt to retrieve them

function allStorage() {

var archive = [],
keys = Object.keys(localStorage),
i = 0, key;

for (; key = keys[i]; i++) {
archive.push( key + '=' + localStorage.getItem(key));
}

document.getElementbyId("result").innerHTML = archive;
}
<div id="result"></div>


<button onclick="allStorage()">Show Local Storage</button>

有谁知道我可能哪里出错了?

据我所知:变量设置正确,因为它们可以在控制台中访问。但是,当我单击运行该函数时,窗口或控制台中没有任何反应。

我正在寻找的结果是:

lastnameSmithlastnameOrangelastnameGreenlastnamePink

设置范围为<div id="result">

最佳答案

试试这个,localStorage 的键名称应该是唯一的,否则它将覆盖这些值。

HTML

  <div id="result"></div>
<button onclick="allStorage()">Show Local Storage</button>

JS

 // Setting some values in the local storage
localStorage.setItem("lastname1", "Smith");
localStorage.setItem("lastname2", "Orange");
localStorage.setItem("lastname3", "Green");
localStorage.setItem("lastname4", "Pink");


// Attempt to retrieve them

function allStorage() {

var archive = [],
keys = Object.keys(localStorage),
i = 0, key;

for (; key = keys[i]; i++) {
archive.push( key + '=' + localStorage.getItem(key));
}

document.getElementById("result").innerHTML = archive;
}

关于javascript - 检索本地存储的多个值并在 div 元素中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58940331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com