最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Saving table data to HTML5 LocalStorage - Stack Overflow

programmeradmin2浏览0评论

I've created a JSFiddle Here

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.

I've created a JSFiddle Here

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.

Share Improve this question edited Jan 29, 2015 at 4:12 Lumi Lu 3,3051 gold badge13 silver badges21 bronze badges asked Jan 29, 2015 at 3:42 Sethe23Sethe23 2,6824 gold badges20 silver badges18 bronze badges 1
  • you wish to save the whole table, not just data within the table? – taesu Commented Jan 29, 2015 at 3:47
Add a ment  | 

2 Answers 2

Reset to default 2

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

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);

Fiddle

Maybe you can save it as a JSON string

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);
发布评论

评论列表(0)

  1. 暂无评论