这里的问题是它永远不会进入 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;
}
最佳答案
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.');
}
}
关于javascript - 第一次访问时 - 弹出一个 div 询问用户名,然后将其和日期存储在本地存储中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18987094/