localStorage getItem问题

时间:2015-02-09 20:13:37

标签: javascript html local-storage

我的页面上有多个输入,并将来自它们的数据存储在< span> ......< / span>按钮单击(因为文本被输入并存储,它被认为不会从那些< span>字段中消失。)

        var newDate = document.getElementById('event_date');//my input
        var storageNewDate = newDate.value;//my text inside <input> which transfers it to <span>
        localStorage.setItem('Date', storageNewDate);//the data is stored

但是我无法从localStorage检索存储的数据。我的Web开发人员工具向我显示存储的数据存在,但是当我转动或重新加载页面时,我得到了我的&lt; span&gt;田野空了。

    var insideSpanTags = document.getElementsByClassName("spanEvent");//all my <spans> 
      insideSpanTags.innerHTML = localStorage.getItem('Date');// I want my stored data to be shown there   

那么,我怎样才能将我的存储数据放在&lt; span&gt;每次刷新或重新加载页面时都会标记?

1 个答案:

答案 0 :(得分:1)

您需要循环选择器

var insideSpanTags = document.getElementsByClassName("spanEvent");

for(var i=0; i<insideSpanTags.length; i++){
      insideSpanTags[i].innerHTML = localStorage.getItem('Date');
}

因为insideSpanTags是所有元素的数组集合。


由于您正在使用对象数组,因此需要将{1}}对象数组JSON.stringify转换为localStorage。要检索值,请使用JSON.parse

<强> jsBin demo

var insideSpanTags = document.getElementsByClassName("spanEvent");
var events = [
    {
        'date': '7-1-2015',
        'event': 'Event Title',
        'participants': 'John, Robert',
        'description': 'Football'        
    },
    {
        'date': '23-1-2015',
        'event': 'Event Title 2',
        'participants': 'Peter, Rob',
        'description': 'Basketball'        
    },
];


// On Save, use this to store your events:
localStorage.evts = JSON.stringify( events );
// Now events are stored in LS


// After it's saved but also while first reading use:
var storedEvts = JSON.parse( localStorage.evts );
console.log( storedEvts );


// Just to test
storedEvts.forEach(function(el, idx){
  insideSpanTags[idx].innerHTML = el.date;
});

// Result:
//> 7-1-2015
//> 23-1-2015