【发布时间】:2019-01-13 19:46:21
【问题描述】:
我有一个使用 localstorage 将非空白 ID #M1 存储到 #M48 的循环 但还需要一种方法来检索本地存储变量。我怀疑答案与 JSON.stringify 有关。
我该怎么做?
<form>
<input type = "text" id = "M1" />
<input type = "text" id = "M2" />
<input type = "text" id = "M3" />
...
</form>
<script> //store the variables
$max_entrants = 48;
for ($i = 0; $i <= $max_entrants; $i++) {
localStorage.setItem("LS-MEM_" +$i, "M" +$i);
}
</script>
<script> //retrieve the variables into a form using ID#s
$max_entrants = 48;
for ($i = 0; $i <= $max_entrants; $i++) {
$wrench = localStorage.getItem("LS-MEM_" +$i);
$("#M" +$i).val($wrench);
}
</script>
上面的脚本已经过测试并且失败了。
<div id = "result"></div>
<script>
document.getElementById("result").innerHTML = localStorage.getItem("LS-MEM_2");
</script>
输出为 ======>> "M2"
这可以解决吗?
【问题讨论】:
-
我认为您还想从文本框中获取值。围绕
getElementById做一些研究。 -
答案可以这样添加和标记吗?
-
是的。我怀疑答案与 JSON.stringify 有关。如果您发布有效的答案,我会将其标记为有帮助和解决方案。
-
不清楚您要做什么。您的代码示例仅存储键/值对,例如
LS_MEM_1: 'M1',因此您想要“修复”的输出是预期的。你希望得到什么输出? -
您的代码运行良好。你还期待什么?它正确地将值存储在本地存储中,获取它们并将它们分配给相应的文本框。见一个工作小提琴here。