我构建了一个应用程序,然后我使用PhoneGap Build构建。目的是运行代码(在加载应用程序时每天var Quotes
启动一次)。
在调试它为什么不起作用时,我注意到在控制台中我收到了我的消息"本地存储没有工作"。这意味着我应该确保可以读取本地存储的初始localstorage.getItem
返回null
。所以我的代码永远不会被执行。
我做错了什么?
function onDeviceReady() { //Do something when the app on device is loaded
var localVal = localStorage.getItem('DateOpened');
if(localVal == null){
console.log("LocalStorage did not work...")}
else
{
var tempd = new Date(); //Get today's date
var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
if(localVal.localeCompare(str) == -1)
{
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
}
答案 0 :(得分:1)
最初,本地存储中没有DateOpened
项,因此您的代码将遵循“无效”分支,因为getItem
会返回null
存在。该分支从未在DateOpened
中设置任何内容,因此......您将始终遵循该分支。
如果设备具有本地存储空间,则修复不会跳过代码设置DateOpened
。
还存在一个无关的问题:您的var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear()
不会产生一个字符串,它会产生一个由将这些值加在一起形成的数字,因为它们是所有数字。您以后的localeCompare
将失败,因为它不是字符串。您还有错误顺序的字段,以进行有意义的文本比较 - 您需要先按年份,然后按月,然后按一天。
这是一个最小的修复,请参阅注释:
function onDeviceReady() {
var tempd = new Date();
// Note that by adding strings in there, we end up with a string instead of adding.
// Note the order: Year first, then month, then day.
// Also, since we display it, we put separators in and add 1 to month (since Jan = 0).
var str = tempd.getFullYear() + "-" + (tempd.getMonth() + 1) + "-" + tempd.getDay();
var localVal = localStorage.getItem('DateOpened');
// If we have no stored value, or it's more than a day old by your definition,
// do your stuff and store the new date
if (localVal == null || localVal.localeCompare(str) < 0) {
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened', str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
答案 1 :(得分:-2)
我认为这对你来说很有帮助。
function onDeviceReady() { //Do something when the app on device is loaded
var localVal = localStorage.getItem('DateOpened');
if (typeof(DateOpened) == "undefined")
console.log("LocalStorage did not work...")}
else
{
var tempd = new Date(); //Get today's date
var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
var allRecords=JSON.parse(localStorage.getItem("DateOpened"));
if(allRecords == -1)
{
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
}