javascript 将表数据保存到 HTML5 LocalStorage
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28206654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving table data to HTML5 LocalStorage
提问by Sethe23
I've created a JSFiddle Here
我在这里创建了一个 JSFiddle
What I'm trying to do is save table data from the following code:
我想要做的是从以下代码中保存表数据:
$('#save').click(function () {
$("#dataTable").find('tbody')
.append($('<tr>')
.append($('<td>')
.text($('#fname').val()))
.append($('<td>')
.text($('#lName').val()))
.append($('<td>')
.text($('#mId').val()))
);
$('#fname').val('');
$('#lName').val('');
$('#mId').val('');
})
I would like to save the <tr>
data, but I'm having trouble finding where to start on parsing that into a savable format.
我想保存<tr>
数据,但找不到从哪里开始将其解析为可保存格式的问题。
采纳答案by Ankush Jain
I have written little bit code to help you.
我写了一点代码来帮助你。
First create a class for the record which you want to store in grid
首先为要存储在网格中的记录创建一个类
function MemberInfo(fName,lName,memberId){
this.FirstName=fname;
this.LastName=lName;
this.MemberId=memberId;
}
the create a function which will loop through all the tr and tds to populate that array, and finally save the JSON data in localStorage
创建一个函数,它将遍历所有 tr 和 tds 以填充该数组,最后将 JSON 数据保存在 localStorage 中
var arr=[];
$("#dataTable").find('tbody tr').each(function(index,item){
var fName=$(item).find('td').eq(0).text();
var lName=$(item).find('td').eq(1).text();
var memberId=$(item).find('td').eq(2).text();
arr.push(new MemberInfo(fName,lName,memberId))
});
localStorage.setItem("memberData",arr);
回答by Ivo
Maybe you can save it as a JSON string
也许您可以将其另存为 JSON 字符串
var data = {
name : $('#fname').val(),
lastname : $('#lName').val(),
memberId : $('#mId').val()
};
localStorage.setItem('member-data', JSON.stringify(data))
then later:
后来:
var data = JSON.parse(localStorage.getItem('member-data') || {})
$('#fname').val(data.name);
$('#lName').val(data.lastName);
$('#mId').val(data.memberId);