1

这里的问题是它永远不会进入 else 语句;我已经尝试创建一个标志来检查它何时进入 if 并更改,但它没有用

var oUser = {};
// This is to add Name to JS
if (!oUser.name) {
    oUser.name = prompt("Enter Name: ") // This is to add Name to JS 
    localStorage.name = oUser.name
    // Now the time
    oUser.date = new Date().toUTCString();
    localStorage.date = oUser.date;
} else {
    var msgDis = document.getElementById('msgDisplay');
    msgDis.innerHTML = "Hi " + localStorage.name + " Welcome back!" + " -->Date: " + localStorage.date;
}
4

2 回答 2

1

oUser.name是未定义的,所以!oUser.name总是会通过。您将 oUser 创建为空对象 ( var oUser = {};),然后检查您从未定义的数据成员。

您应该检查是否设置了 localStorage:

// Declare oUser in the global scope, as an empty object
var oUser = {};
// check for browser support of localStorage
if(typeof(localStorage) == 'undefined') {
    // Check failed, alert user
    alert('Your browser does not support the localStorage method!');
} else {
    // wrapping this in a try...catch block, incase cookies are disabled
    try {
        // Attempt to pull oUser (by key) from localStorage, failure results
        // in oUser being an empty object.
        oUser = JSON.parse(localStorage.getItem('oUser'))||{};
        // Now check if oUser.name is NOT set
        if(!oUser.name) {
            // prompt user for a name
            oUser.name = prompt("Enter Name: ");
            // insert current date
            oUser.date = (new Date()).toUTCString();
            // save oUser in localStorage, stringified
            localStorage.setItem('oUser',JSON.stringify(oUser));
        } else {
            // oUser.name was set, welcome them back
            var msgDis = document.getElementById("msgDisplay");
            msgDisplay.innerHTML = "Hi " + oUser.name + " Welcome back! -->Date: " + oUser.date;
        }
    } catch(e) {
        // Cookies are disabled, which threw an error, alert the user
        alert('To use localStorage, you need to enable cookies.');
    }
}
于 2013-09-24T16:39:02.003 回答
0

只是我想出的一个很好的例子:
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) 
    }
};
于 2013-09-24T19:55:11.207 回答