jquery移动页面无法使用localstorage

时间:2014-10-28 20:20:24

标签: jquery-mobile cordova local-storage

的PhoneGap

Jquery mobile

不使用Chrome浏览器或iOS。

我正在努力实施"最近的历史"功能,如果用户访问页面,页面标题将存储在localStorage中,然后再检索。

我在页面上有一个按钮,单击该按钮会将(键,值)添加到localstorage。

$(document).on('tap','#getMeThere',function(){
var title = $('#serviceTitle').text();
var duplicate = false;
for (var i = 0; i < window.localStorage.length; i++){//check if service is already in storage
   if(window.localStorage.getItem(window.localStorage.key(i)) == title){
    duplicate = true;
    break;
   }
}

if(duplicate == false){//does not exist in array
    window.localStorage.setItem(title,title); //add to local storage
}
});

我在另一个页面上有另一个按钮,单击该按钮时,会加载一个新页面并在列表视图中显示localStorage中的所有项目。

$(document).on('pagebeforecreate', '#recent', function(){//display services that user has visited

    if(window.localStorage.length == 0){
    console.log('local storage length=' + window.localStorage.length);
    $('#recentEmpty').text("You haven't visited any services yet! Any services you visit will     show up on this page.");
}
else{
for (var i = 0; i < window.localStorage.length; i++){
 $("#recentList").append($("<li><a href='#ymca' data-transition='slide'>YMCA</a></li>"));
}
     console.log('local storage length=' + window.localStorage.length);
}
});

案例1:问题是如果我打开我的应用程序。我点击第二个按钮,查看&#34;您还没有访问过...&#34;。没关系。然后我转到另一个页面并单击第一个按钮向localStorage添加值。当我再次点击第二个按钮时,我应该看到一个列表项,而我仍然会看到&#34;您还没有访问过#34;。即使我在检查元素时看到localStorage.setItem成功并且localStorage中有1个值。我需要刷新浏览器才能看到列表项。

案例2:我打开我的应用程序,单击第一个按钮添加到存储,然后单击第二个按钮显示它,我的最近历史页面正确显示1个列表项,无需刷新。

这似乎是某种缓存问题。或者我可能需要以某种方式刷新页面?

1 个答案:

答案 0 :(得分:0)

您正在使用pagebeforecreate,它在创建页面之前运行,只执行一次。您可能需要pagebeforeshow