HTML5 localStorage key order

我是研究僧i 提交于 2019-12-31 01:53:08

问题


I have some div's on my page coded as

<div id="1">Click Me to load corresponding dynamicList</div><ul class="dynamicList"></ul>
<div id="2">Click Me to load corresponding dynamicList</div><ul class="dynamicList"></ul>
<div id="3">Click Me to load corresponding dynamicList</div><ul class="dynamicList"></ul>
<div id="4">Click Me to load corresponding dynamicList</div><ul class="dynamicList"></ul>
<div id="5">Click Me to load corresponding dynamicList</div><ul class="dynamicList"></ul>

Now on click of any of the div's, an AJAX call is made which returns the dynamic List as;

<li>Some content 1</li>
<li>Some content 2</li>
<li>Some content 3</li>

I want to store the above dynamic List in localStorage, after the 1st AJAX call. So I write;

var key = $(selectedDiv).attr('id');     
var value = str;     //str = Returned AJAX response of li's
localStorage.setItem(key, value);

Now on the next page load, I want to append all the dynamicList's (all those which user had clicked earlier) at the right place in the DOM (So an AJAX call is not made for the data during next click)

for (i=0;i<localStorage.length;i++) 
{
var key = localStorage.key(i);
    if(key != null) 
    {
    var value = localStorage.getItem(key); 
    $("#"+i).next(".dynamicList").empty();
    $("#"+i).next(".dynamicList").append(value);
    }
}

Now there seems to be some issue in the order of the localStorage, as the right dynamicList is not getting appended at the right place. I guess there is some issue for the line

var key = localStorage.key(i);

Please let me know how do I fix this.


回答1:


Don't rely on the order of localStorage keys. You can iterate through all available keys on localStorage using localStorage[n], but that refers to a key (string) which can be used with localStorage[str_key] or localStorage.getItem(str_key).

In your case, you've confused the index of the localStorage key names with the name you assigned to the item. Therefore, don't use the key index, but your value key:

for (i=0;i<localStorage.length;i++) 
{
var key = localStorage.key(i);
    if(key != null) 
    {
    var value = localStorage.getItem(key); 
    $("#"+key).next(".dynamicList").empty();
    $("#"+key).next(".dynamicList").append(value);
    }
}



回答2:


Make a separate object in the localStorage to :

  • Avoid pollution of the storage space (if you just fill the root node, you'll have a hard time adding extra features later)
  • Get sorting back :-)

localStorage.specificStorage = {}; // Maybe even []



来源:https://stackoverflow.com/questions/8340845/html5-localstorage-key-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!