正如承诺的那样,我为您准备了一个演示。为了便于理解,我在代码中放了很多 Remarks。它不使用 Json,而是使用异步函数来循环本地存储。它工作得很好。最重要的是它非常可靠,并且永远不会破坏本地存储。
您可以添加和删除用户,但可以接受各种可能性,因为您将从备注中阅读。它可以作为基础数据库在LocalStore中存储数据。
演示
http://jsfiddle.net/3vynv918/
jQuery
$( document ).ready(function() {
// an async function to loop around with ease
var asyncFor = function(params) {
var defaults = {
total: 0,
limit: 1,
pause: 10,
context: this
},
options = $.extend(defaults, params),
def = $.Deferred(),
step = 0,
done = 0;
this.loop = function() {
if (done < options.total) {
step = 0;
for (; step < options.limit; step += 1, done += 1) {
def.notifyWith(options.context, [done]);
}
setTimeout.apply(this, [this.loop, options.pause]);
} else {
def.resolveWith(options.context);
}
};
setTimeout.apply(this, [this.loop, options.pause]);
return def;
};
$(document).on( "click", "#sub", function() {
var name = $('#user').val();
var id ="";
//create a random id for the user so we can distinguish him in local storage incase of Possible duplicate first names
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 10; i++ )
id += possible.charAt(Math.floor(Math.random() * possible.length));
//store the data from the form to localstorage. we use user as the kind of dataset so it will enable to store as many datasets as possible. eg stock, places, locations. So you can group data. In this example we are storing Users
localStorage.setItem(id, 'user['+name+'#name]' ); // you can add many form items by seperating them by # eg name#surname#address. I put #name as an example, but in this demo we dont read that. So we call that spare data as it does nothing, although it gets stored for each user.
$('#usersname').html(name);
show_localstore()
});
// get all items from local storage and show them
function show_localstore() {
var mylistitems = "";
$('#storage').empty();
asyncFor({
total: localStorage.length,
context: this
}).progress(function(step) {
var propertyName = localStorage.key(step);
var keyv = propertyName;
var value = localStorage.getItem(propertyName);
//check the dataset if its user. If you have other datasets then change user to that dataset
if (value.indexOf('user') > -1) {
var matches = value.match(/\[(.*?)\]/);
if (matches) {
var words = matches[1];
var match = words.split('#');
var username = match[0]; // matches the first item, if you have many then set up variables and change the match value eg surname = match[1] address = match[2] etc
$("#storage").append('<p><a>user_id='+keyv+'<a>--username='+username+'</a></p>');
}}
}).done(function() {
});
};
//delete localstore item by selecting the User_id value.
$(document).on( "click", "#delsub", function() {
var id = $('#deluser').val();
localStorage.removeItem(id);
show_localstore()
});
show_localstore()
});