从下面的代码中,我可以set or store
我输入的数据 localStorage
,但我不确定如果我刷新页面,如何在视图页面中检索和显示相同的数据。我试过localStorage.getItem()
.每次单击Save
按钮时都会显示输入的数据,这很好,很完美。但是如果我刷新页面,那么它不会显示任何内容,它正在重置,即使我也在我的视图上刷新页面,我也想show/display the same eariler Saved data
。请让我知道该怎么做?提前感谢!
.html:
<button class = "btn btn-primary" data-toggle = "modal" data-target = "#myModal">
Click
</button>
<div class = "modal fade" id = "myModal" tabindex = "-1" role = "dialog"
aria-labelledby = "myModalLabel" aria-hidden = "true">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<button type = "button" class = "close" data-dismiss = "modal" aria-hidden = "true">
×
</button>
</div>
<div class = "modal-body">
<textarea id="content"></textarea>
<br /><br/>
<button id="saveBtn">Save</button>
<div id="output" style="overflow: auto; height: 75px; width: 450px;">
</div>
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-default" data-dismiss = "modal">
Close
</button>
</div>
</div>
</div>
</div>
.js:
$(saveBtn).click(function(){
var noteContent = $(content).val();
var outputarea = $(output);
var info = [{ "content":"Doe" }];
$.each(info, function() {
i=0;
info[i].content = noteContent;
outputarea.append('<br>content:' + info[i].content + '<hr />');//it is appending the data to "outputarea" on clicking of Save button, but I want to show same data even if I refresh the page also(from localStorage) - how to do this
localStorage.setItem('info[i].content',info[i].content);
//localStorage.getItem(info[i].content);
i++;
function recallNote(){
$(content).val(info[i].content);
}
});
});
小提琴可用。
最终解决方案:链接
var info = [];
function allStorage(arr) {
keys = Object.keys(localStorage);
//console.log(keys);
i = keys.length;
while ( i-- ) {
arr.push( { content : localStorage.getItem(keys[i])} );
}
}
allStorage(info);
console.log(info);
var outputarea = $(output);
info.forEach((val)=>{
outputarea.append('<br>content:' + val.content + '<hr />');
})
$(saveBtn).click(function(){
var noteContent = $(content).val();
var obj = {content : noteContent};
info.push(obj);
console.log(info);
outputarea.append('<br>content:' + info[(info.length-1)].content + '<hr />');
localStorage.setItem('info['+(info.length-1)+'].content',info[(info.length-1)].content);
function recallNote(){
$(content).val(info[info.length-1].content);
}
});