Jquery mobile:检测是否是用户首次启动应用程序

时间:2014-03-21 17:21:04

标签: jquery-mobile

嗨,我试图检测用户是否第一次使用此代码启动我的应用程序。但在$(document).on('pageshow','#welcome-page', function(){部分,我的变量firstlaunch始终未定义。你能帮我搞清楚该做什么吗?

由于

var firstlaunch;


$(function(firstlaunch) {
    firstlaunch = parseInt(window.localStorage.getItem("firstlaunch"));
    //store 0 for next time
    if ( firstlaunch == null || typeof firstlaunch == 'undefined' || isNaN(firstlaunch) ) {     
        firstlaunch = 1;
        window.localStorage.setItem("firstlaunch", 0);
    }
});

$(document).on('pageshow','#welcome-page', function(){

console.log("firstlaunch pageshow #welcome-page = "+firstlaunch);
console.log("typeof firstlaunch pageshow #welcome-page = "+typeof firstlaunch);
  if ( firstlaunch ==1 || typeof firstlaunch == 'undefined' || isNaN(firstlaunch) ){
               //do things if first visit
        } else if (firstlaunch == 0) {
              //do things if not first visit
        } else {
            console.log('Error :  firstlaunch ='+firstlaunch);
        }

});

2 个答案:

答案 0 :(得分:0)

localStorage.getItem()调用如果不存在则返回null。

最简单的方法是:

$(document).one('pageshow','#welcome-page', function(){
    var noRunCount = (localStorage.getItem("runCount") == null);
    if (noRunCount) {
        // You know it's the first time this is run because 
        // the variable isn't even defined yet
        localStorage.setItem("runCount", 1);
    } else {
        // The variable exists, so it must have been set by your app
        localStorage.setItem("runCount", (localStorage.getItem("runCount") + 1));
    }
}

这里要注意的一件事是使用$(document).one('pageshow', )代替$(document).on('pageshow', )。这使得此块中的逻辑仅在第一次加载欢迎页面时执行。

答案 1 :(得分:0)

谢谢大家。 我选择了@ezanker的解决方案,因为它接近我的代码并且很简单。 再次感谢你。

$(document).on("pageshow", "#welcome-page", function(){
    alert(IsFirstLaunch());
});

function IsFirstLaunch(){
    var fl = window.localStorage.getItem("firstlaunch");
    if (fl && parseInt(fl) == 0){
        return false;
    } else {        
        window.localStorage.setItem("firstlaunch", "0");
        return true;
    }
}