HTML5的localStorage键顺序顺序、localStorage

2023-09-10 15:47:37 作者:靜待、彼岸婲開ゞ

我有一些div的我的网页上codeD为

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>

现在就点击任何的div的,一个AJAX调用时返回的动态列表作为;

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>

我要存储在localStorage的上述动态列表,第一个AJAX调用后。所以我写;

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);

现在在接下来的页面加载,我要追加所有dynamicList的在DOM中的正确的地方(所以一个AJAX调用是不是在接下来的点击数据做)(所有这些用户此前点击)

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);
    }
}

现在似乎有在localStorage的顺序一些问题,如右图dynamicList是没有得到追加在正确的地方。 我想有一些问题的行

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.

推荐答案

不要依赖的的localStorage 键的顺序。您可以通过所有可用的钥匙放在的localStorage 重复使用的localStorage [N] ,但这指的是关键(串)可与使用的localStorage [str_key] localStorage.getItem(str_key)

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).

在你的情况,你迷茫的的localStorage 键的名称与分配给该项目的名称索引。因此,不使用关键指标,但你的价值的关键:

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);
    }
}
 
精彩推荐
图片推荐