Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从本地存储获取getElementByID_Javascript - Fatal编程技术网

Javascript 从本地存储获取getElementByID

Javascript 从本地存储获取getElementByID,javascript,Javascript,我正试图从存储在localStorage中的键中getElementById。我的本地存储中有以下数据: 问题1=答案1 问题2=回答2等 和脚本: <script> if (localStorage.getItem("question1") === null) { } else { document.getElementById('question1').innerHTML = (localStorage.getItem("question1")); } if (loca

我正试图从存储在
localStorage
中的键中
getElementById
。我的本地存储中有以下数据:

问题1=答案1

问题2=回答2等

和脚本:

<script>
if (localStorage.getItem("question1") === null) {
} else {
    document.getElementById('question1').innerHTML = (localStorage.getItem("question1"));
}

if (localStorage.getItem("question2") === null) {
} else {
    document.getElementById('question2').innerHTML = localStorage.getItem("question2");
}
</script>

您可以使用
spread
操作符执行以下操作:

const items = { ...localStorage };

for (x in items){
    document.getElementById(x).innerHTML = localStorage.getItem(x);
}
尝试:

设i=1;
const item=localStorage.getItem(“问题”+i)
while(项目){
document.getElementById(x).innerHTML=item
i+=1;
const item=localStorage.getItem(“问题”+i)
}
注意:

const items = { ...localStorage };

可以迭代非问题

您必须使用json.stringify将其作为json数组保存到localstorage,然后当您从localstorage读取1次时,执行json.parse以获取您的对象列表。然后你可以在上面迭代。太棒了,太简单了。我不知道这件事。工作非常好!非常感谢你!完成!对不起,我是新手。
const items = { ...localStorage };