This question already has answers here: What do querySelectorAll and getElementsBy* methods return?                                                                    (9个答案)                                                                                        5年前关闭。                                我的页面上有多个输入,并通过单击按钮将它们中的数据存储在 ... 内(由于键入并存储了文本,因此认为不会从这些字段中消失)。 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开发人员工具向我显示存储的数据存在,但是当我打开或重新加载页面时,我的字段为空。 var insideSpanTags = document.getElementsByClassName("spanEvent");//all my <spans> insideSpanTags.innerHTML = localStorage.getItem('Date');// I want my stored data to be shown there因此,每次刷新或重新加载页面时,如何在标记中获取存储的数据? (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 您需要循环选择器var insideSpanTags = document.getElementsByClassName("spanEvent");for(var i=0; i<insideSpanTags.length; i++){ insideSpanTags[i].innerHTML = localStorage.getItem('Date');}原因insideSpanTags是所有元素的Array集合。由于使用的是对象数组,因此需要将对象数组JSON.stringify放入localStorage。比使用JSON.parse检索值:jsBin demovar 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 teststoredEvts.forEach(function(el, idx){ insideSpanTags[idx].innerHTML = el.date;});// Result://> 7-1-2015//> 23-1-2015 (adsbygoogle = window.adsbygoogle || []).push({});
07-24 17:17