列出localstorage [英] Listing localstorage

查看:180
本文介绍了列出localstorage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b $ pre $ function save(title,url)
{
为(var i = 1; i< localStorage.length; i ++)
{
localStorage [saved-title_+ i +] = title;
localStorage [saved-url_+ i +] = url;



函数listFavs()
{
for(var i = 1; i< localStorage.length; i ++){
console.log(localStorage [saved-fav-title_+ i +));当有人点击这个时,save()会发生:




/ p>

  onclick =save(\''+ title +'\',\''+ tab.url +' \');> '+ title +'< / a>'; 

但是 ...不显示保存的localStorages,如何我应该让它工作?

解决方案

可能是因为你正在使用键'已保存-title_'+ i 保存值,'saved-fav-title_'+ i 来检索它?



区别在于 fav - 部分。

你的localStorage的枚举必然会产生错误不能保证它里的所有项目都有一个与'saved-fav-title_'+ i 提供的模式相匹配的密钥 - 实际上它保证不会如你所愿你自己输入的项目是'saved-url _'+ i 形式的键

想要用一个匹配模式的键正确枚举项目使用

 函数listFavs(){
var key;
for(var i = 0,len = localStorage.length; i< len; i ++){
key = localStorage.key(i);
if((/^saved-fav-title_/).test(key)){
console.log(localStorage.getItem(key);
}
}
}


I did my own feature using this:

function save(title, url)
{
 for (var i = 1; i < localStorage.length; i++) 
 {
  localStorage["saved-title_" + i + ""] = title;
  localStorage["saved-url_" + i + ""] = url;
 } 
}

function listFavs()
{
 for (var i = 1; i < localStorage.length; i++) {
    console.log(localStorage["saved-fav-title_" + i + ""]);
 }
}

save() happens when someone clicks on this:

onclick="save(\'' + title + '\', \'' + tab.url + '\');"> ' + title + '</a>';

However... it doesn't show the saved localStorages, how am I supposed to make it work?

解决方案

Might it be because you are using the key 'saved-title_' + i to save the value and 'saved-fav-title_' + i to retrieve it?

The difference is the fav- part.

And your enumeration of the localStorage is bound to create errors as there is no guarantee that all items in it have a key that matches the pattern provided 'saved-fav-title_' + i - actually it is guaranteed to not be so as you are yourself inputting items with keys in the form of 'saved-url_'+ i.

So, if you want to properly enumerate the items with a key matching a pattern use

function listFavs(){
    var key;
    for (var i = 0, len = localStorage.length; i < len; i++){
        key = localStorage.key(i);
        if ((/^saved-fav-title_/).test(key)) {
            console.log(localStorage.getItem(key);
        }
   }
}

这篇关于列出localstorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆