简体   繁体   中英

On first time visit- popup a div asking user name, then store it and the date on local storage

the problem here is it never goes into the else statement; I already tried creating a flag to check when it goes into the if and changing but it didn't work

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;
}

oUser.name is undefined, so !oUser.name will always pass. You're creating oUser as an empty Object ( var oUser = {}; ), then checking a data member you never defined.

You should be checking if the localStorage is set:

// 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.');
    }
}

Just a neat example I came up with:
LocalStorage the fun way:

LIVE DEMO

LocalStorage Script:

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);
    }
};

Basic usage:

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

In your case you can use this script like:

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;  

}

if you want to delete that item from your localStorage than just do:

LS.del('oUser');

If you want to add more features / fixes,
here's the script reverse-engeenered:

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) 
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM