我想要做的是将表中的所有数据存储到本地存储中,这样如果我刷新或关闭浏览器并再次重新打开,则内容仍然是刷新或关闭之前的内容。如果我删除一个特定的行,它也应该在localstorage中被删除,这样如果我刷新页面它就不会回来。
我的问题是,它只在本地存储中存储了一行表,其他行未保存。
current output:
http://jsfiddle.net/4GP2h/57/
答案 0 :(得分:1)
匆忙?这是fiddle:
现在,您要将"dataSet"
localStorage
项设置为用户添加的最后一行:
var data = [
$('#name').val(),
$('#age').val(),
$("[name='gender']:checked").val(),
"<button class='delete'>Delete</button>"
];
oTable.row.add(data).draw();
//Assignment operator!
var dataset = JSON.stringify(data);
localStorage.setItem('dataSet', dataset);
因此,只保存一行。相反,您需要使用多维数组来容纳多个行。
"dataSet"
localStorage
项目输出数据:
//Use a try/catch loop to make sure that no errors come up while parsing the JSON of our localStorage
var dataSet;
try{
dataSet = JSON.parse(localStorage.getItem('dataSet')) || [];
} catch (err) {
dataSet = [];
}
/*
I did not add this in here, but you might want to since if our item returns an empty array, it either has an empty array in it, in which case the following code won't affect anything, or it has a localStorage item we don't want in it, in which case this will fix that.
if (!dataSet.length) localStorage.setItem('dataSet', '[]')
*/
$('#myTable').dataTable({
"data": [],
[...]
});
oTable = $('#myTable').DataTable();
//Loop through dataSet to add _all_ of the rows.
for (var i = 0; i < dataSet.length; i++) {
oTable.row.add(dataSet[i]).draw();
}
"dataSet"
localStorage
项:
var data = [
$('#name').val(),
$('#age').val(),
$("[name='gender']:checked").val(),
"<button class='delete'>Delete</button>"
];
oTable.row.add(data).draw();
//Push the new data into dataSet. DO NOT assign dataSet to data.
dataSet.push(data);
//Update the localStorage item.
localStorage.setItem('dataSet', JSON.stringify(dataSet));
"dataSet"
localStorage
项目中删除数据:
var row = $(this).closest('tr');
//Find the index of the row...
var index = $("tbody").children().index(row);
oTable.row(row).remove().draw();
//...and remove it from dataSet.
dataSet.splice(index, 1);
localStorage.setItem('dataSet', JSON.stringify(dataSet));
答案 1 :(得分:0)
好吧,您的问题是,每次点击“保存”按钮时,您都会将数据集保存为当前行:
var data = [
$('#name').val(),
$('#age').val(),
$("[name='gender']:checked").val(),
"<button class='delete'>Delete</button>"];
oTable.row.add(data).draw();
var dataset =JSON.stringify(data);
localStorage.setItem('dataSet', dataset);
尝试将最新行附加到总数据集并保存,但