HTML5显示具有特定内容的localStorage元素

时间:2013-05-13 11:08:28

标签: javascript html5 local-storage

我有以下代码:

<script type="text/javascript">
        for (i=0;i<localStorage.length;i++) 
        {
            var key = localStorage.key(i);
            if(key == "5") 
            {
                var value = localStorage.getItem(key); 
                document.write(value + "<br />");
            }
        }
</script>

我尝试打印具有特定内容的所有元素 - 可以进行演示 是5,但我无法得到它。

任何帮助?

2 个答案:

答案 0 :(得分:2)

鉴于LocalStorage(因为所有基于密钥的存储系统)不允许多个元素具有相同的密钥,因此有一些解决方案:

  1. 数组存储在单个键中并迭代该数组。记住LocalStorage只支持字符串,因此在写入/读取LocalStorage时必须进行字符串化/解析:

    var elements = [], 
        elements[0] = {name: "Alpha"}, 
        elements[1] = {name: "Beta"}, 
        elements[2] = {name: "Gamma"};
    
    // Save
    localStorage.setItem(key,JSON.stringify(elements);
    // Read
    var elements = JSON.parse(localStorage.getItem(key));
    
  2. 使用“点表示法”路径作为键并实现某种路径解析:

    var elements = [], 
        elements[0] = {name: "Alpha"}, 
        elements[1] = {name: "Beta"}, 
        elements[2] = {name: "Gamma"}, 
        elementsKey = 5;
    
    // Save
    for(var e = 0; e < elements.length; e ++) {
        // Elements get stored in "5.0", "5.1", "5.2", …
        var key = elementsKey + "." + e;
        localStorage.setItem(key,JSON.stringify(elements[e]);
    }
    
    // Read
    var baseKey = 5; // This is the "root" key to search for children
    for (var e = 0; e < localStorage.length; e++) {
        var key = localStorage.key(e);
        var subKey = key.split(".").pop(); // this is the "sub" key for this children element
        if(key.indexOf(baseKey) >= 0) {
            var element = localStorage.getItem(key);
        }
    }
    
  3. 现在我不知道你在这些钥匙里面存放了什么,但这应该给你一个很好的起点。

答案 1 :(得分:1)

您需要创建本地存储变量在迭代之前,您的迭代代码将在页面加载发生时触发

window.localStorage.setItem("1", "AKSAHY");
window.localStorage.setItem("2", "John");
window.localStorage.setItem("3", "Manu");
window.localStorage.setItem("4", "Albert");
window.localStorage.setItem("5", "Mathew");


 for (i=0;i<localStorage.length;i++) 
        {
            var key = localStorage.key(i);
            if(key == "5") 
            {
                var value = localStorage.getItem(key); 
                alert(value + "<br />");
            }
        }

检查演示: - DEMO