2016-03-07 48 views
0

我构建了一个应用程序,然后使用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); 
    } 
} 
} 

回答

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

我有一个怀疑,因为localVar的是从来没有设置也将是零。谢谢TJ,我会看看这是否有效。 – Badrush

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