只是我想出的一个很好的例子:
LocalStorage有趣的方式:
现场演示
本地存储脚本:
var LS = {
get : function(id) {
var item=localStorage.getItem(id);
return item?(item.charAt(0)=='{'?JSON.parse(item):item):{};
},
set : function(id, key) {
var k=typeof key=="object"?JSON.stringify(key):key;
return localStorage.setItem(id,k);
},
del : function(id){
return localStorage.removeItem(id);
}
};
基本用法:
LS.set('SomeItemID', "String"||Object ); // Store a String or even an Object!
LS.get('SomeItemID'); // Get your String or your Object;
LS.del('SomeItemID'); // Deletes that LocalStorage item
在您的情况下,您可以使用以下脚本:
var oU = LS.get('oUser');
// if oUser exists as a LocalStorage key name, "oU" should now look like:
// oU = {name:"somename", date:"somedate"};
if(!oU.name){
oU.name = prompt("Enter Name: ");
oU.date = new Date().toUTCString();
LS.set('oUser', oU); // Store back the whole object
}else{
var msgDis = document.getElementById('msgDisplay');
msgDis.innerHTML = "Hi " + oU.name + " Welcome back!" + " Date: " + oU.date;
}
如果您想从 localStorage 中删除该项目,而不仅仅是这样做:
LS.del('oUser');
如果您想添加更多功能/修复,
这里是反向工程的脚本:
var LS = {
get : function(id) {
var item=localStorage.getItem(id); // Read LocalStorage(id)
if(item){
if(item.charAt(0)=='{'){ // If is String has "{" (is an JSON)
return JSON.parse(item); // Parse to get the Object
}else{
return item; // else return that string
}
}else{
return {}; // return an empty object
}
},
set : function(id, key) {
var k;
if(typeof key=="object"){ // If we're about to store an Object
k = JSON.stringify(key); // transform it to String
}else{
k = key; // else store whatever is key
}
return localStorage.setItem(id,k); // Send to LocalStorage
},
del : function(id){
return localStorage.removeItem(id);// Delete LocalStorage(id)
}
};