我有一个HTML表,用户可以将单个行添加到。我希望用户能够离线保存此此功能,以便刷新后表上的数据保留。有人告诉我这是最简单的方法,但是如果有人有其他建议,我有张开的耳朵。
$(document).ready(function(){
var count = 1;
var table = "You fucked up yo";
$('#add').click(function addRow(){
var model = $('#Model').val();
var size = $('#Size').val();
var resolution = $('#Resolution').val();
var backlight = $('#Backlight').val();
var pins = $('#Pins').val();
var touch = $('#Touch').val();
$('#screens').append("<tr id='row"+count+"'><td>"+count+"</td><td id
='model"+count+"'>"+model+"</td><td id ='sizes"+count+"'>"+size+"</td><td
id
='resolution"+count+"'>"+resolution+"</td><td id
='backlight"+count+"'>"+backlight+"</td><td id ='pins"+count+"'>"+pins+"
</td><td id ='touch"+count+"'>"+touch+"</td>");
var key = "table"+count;
count++;
});
$('#remove').click(function removeRow(){
var row = $('#row').val();
$('table#screens tr#row'+row).remove();
});
$('#save').click(function save(){
var table = $('#screens').html;
localStorage.setItem("Table", table);
alert('yo');
});
$('#open').click(function open(){
$('#screens').html = localStorage.getItem("Table");
alert('yo');
});
});
解决此问题的最佳方法是使用json存储您的表值,而只是将该结构存储在localstorage或数据库中。但是要回答您的问题,我认为这是您从LocalStorage中存储和检索表结构所需的内容。希望这是您需要的。
<!DOCTYPE html>
<html>
<body>
<div id="tablediv"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("Mytable", "<table><tr><td>col1</td></tr></table>");
// Retrieve
document.getElementById("tableDiv").innerHTML = localStorage.getItem("Mytable");
} else {
document.getElementById("tableDiv").innerHTML = "Your browser does not support Web Storage";
}
</script>
</body>
</html>
您有正确的想法。请确保使用JSON.STRINGIFY()和JSON.PARSE()如下:
var tableData = [{name: "John", email: "jhenry@example.com"}];
// Persist
localStorage.setItem("nameForYourData", JSON.stringify(tableData));
// Retrieve
tableData = JSON.parse(localStorage.getItem("nameForYourData"));
我认为最简单的方法:
var table = $('table').wrap('<table/>').parent().html();
table = JSON.stringify(table);
window.localStorage.setItem('savedTable', table);
// then later
table = JSON.parse(window.localStorage.getItem('savedTable'))
这是小提琴:https://jsfiddle.net/8dhnqy0b/