简体   繁体   English

如何在HTML中以本地存储方式打印存储在数组中的值

[英]How to print value stored in an array in localstorage in html

I have stored the some values in string form in an array oldItems in the localstorage. 我已经将一些值以字符串形式存储在oldItems的数组oldItems中。 Now I want to display that set of string at different places in html. 现在,我想在html的不同位置显示该字符串集。 So all I need is the access to all the strings differently. 因此,我需要的是对所有字符串的访问方式有所不同。

var test2 = JSON.parse(localStorage.getItem("oldItems"));

where I am defining an array test2 and I am printing using id like 我在定义数组test2,并使用id打印,例如

<tr> 
  <td> 1 </td>
  <td>  <p id="test2[0]"></p>  </td>
</tr>

But the following thing is not printing the values stored in the array . 但是接下来的事情不是打印存储在数组中的值。 Is there anything wrong in the code? 代码有什么问题吗? Please help. 请帮忙。 Thanks in advance. 提前致谢。

In <p id="__here__" you cannot state JavaScript statements (the test2[0] you have). <p id="__here__"不能声明JavaScript语句(您拥有的test2[0] )。 They go in the <script> element. 它们放在<script>元素中。 If you want to do this, use: 如果要执行此操作,请使用:

var p = document.querySelector("__any__specific__selector__for__p");
p.id = test2[0];

Following script may be help you : 以下脚本可能会帮助您:

<script>
function displayValues()
{
    var oldItems = JSON.parse(localStorage.getItem('barcodes')) || [];

    for(var i=oldItems.length-1;i>=0;i--)
    {
        var html=document.getElementById("allCodes").innerHTML;
        document.getElementById("allCodes").innerHTML=html+"<br>"+oldItems[i].barcode;      
    }    
    }
displayValues();
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM