【问题标题】:loadItem(); with localStorage (broken)加载项();使用 localStorage(损坏)
【发布时间】:2014-12-07 15:27:51
【问题描述】:

我有两个函数用于 saveItem() 和另一个用于 loadItem();但我需要在“刷新页面时”查看我的项目,我正在使用 localStorage 来保存数据,这是一个 JSON。

var input = document.getElementById('input');

function newItem(list, itemText){
    var item = document.createElement('li');
    item.className = 'item';
    item.innerText = itemText;
    list.appendChild(item);
    saveItem();
}

input.onkeyup = function(evt){
var key = evt.keyCode || evt.whitch;
    if(key == 13){
        itemText = input.value;
        console.log('createITem');
            if(!itemText || itemText == '' || itemText == ' '){
                return false;
            }
                newItem(document.getElementById('ul'), itemText);
     }
}

function saveItem(){
    var items = document.querySelector('li.item');
    var data  = Array.prototype.map.call(items, function(item){
        return [item.innerHTML];
    });
    localStorage.setItem('data', JSON.stringify(data));
}

function loadItem(){
    var items = JSON.parse(localStorage.getItem('data'));
    if(!items){
        return;
    }
    Array.prototype.map.call(items, function(item){
        return newItem(document.getElementById('content-memo'), item[0]);
    });
}

loadItem();

【问题讨论】:

  • 你有什么问题?
  • @ianaya89 我需要查看“浏览器上传”时创建的新项目。
  • 抱歉,我没听懂。 “浏览器上传”是什么意思?是事件吗?我认为您对“加载”事件感到困惑。
  • @ianaya89 当您更新网站时。 :)
  • 我想你的意思是“刷新”网页?

标签: javascript arrays json string parsing


【解决方案1】:

您确定saveItem 有效吗?您的代码显示您调用loadItem,但它没有显示您调用saveItem。无论如何,这就是你的问题所在。

如果您打开开发工具窗格并检查 localStorage(或从控制台,查看是否定义了 localStorage.data),您应该查看它是否正常工作。如果没有,那么loadItem 当然不会按预期工作。

为了map所有li.items,您必须将行更改为:

var items = document.querySelector('li.item');

到这里:

var items = document.querySelectorAll('li.item');

querySelector 只会将第一个结果作为 DOM 对象返回,您不能在其上调用Array.prototype.map。你需要一个类似数组的对象。 queryItemSelectorAll 给你。

就目前而言,saveItem 中的 Array.prototype.map 调用返回一个空数组。这就是在localStorage.data 中设置的内容 - 以及在loadItem 中返回给map 函数的内容。

除此之外,你还有其他烦恼吗?

【讨论】:

  • 是的,我做 list.appendChild(item);在 saveItem(); 之后
  • 您是否尝试过在saveItem 函数中将querySelector 更改为querySelectorAll?它能解决你的问题吗?
  • 您必须按照我的建议将代码从 querySelector 更改为 querySelectorAll。否则,它将无法正常工作。做出改变。然后解释发生了什么。
  • 没关系,现在换个测试。
猜你喜欢
  • 1970-01-01
  • 2013-05-23
  • 2012-12-04
  • 1970-01-01
  • 2019-10-19
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 2012-09-24
相关资源
最近更新 更多