从localStorage获取密钥和值并显示它

时间:2018-03-15 01:53:35

标签: javascript local-storage

我没有获得价值,只得到钥匙。我想从本地存储中获取键和值并在段落中显示,同时使用JavaScript动态生成段落。



<body>
  <p id="para1"></p>
  <p id="para2"></p>
</body>
<script>
  for (var i = 0, len = localStorage.length; i < len; i++) {
    var p1 = document.getElementById("para1");
    var para = document.createElement("P");
    var key = document.createTextNode(localStorage.key(0));
    
    para.appendChild(key);
    p1.appendChild(para);
    console.log("key");

    var p2 = document.getElementById("para2");
    var para2 = document.createElement("P");
    var value = document.createTextNode(localStorage.getitem(key));

    para2.appendChild(value);
    p2.appendChild(para);
    console.log("value");
  }
</script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

var key = document.createTextNode(localStorage.key(0));

也许这应该是

var key = document.createTextNode(localStorage.key(i));