0

我想在安装Cordova/Phonegap应用程序时调用一个函数(用于创建数据库并向其中插入记录)。

事实上,我只想运行这个函数一次。

有什么建议吗?

4

2 回答 2

3

您可以使用LocalStorage

document.addEventListener('deviceready', function()
{
    if (typeof window.localStorage.getItem('firstTime') === 'undefined')
    {
        // Execute some code for the installation
        // ...

        window.localStorage.setItem('firstTime', 0);
    }
});
于 2015-06-10T18:16:41.193 回答
0

虽然添加一个事件侦听器以有效地运行一次,如Ivan 的回答,是正确的,但语法需要稍有不同。

运行以下代码时:

console.log("First time?");
console.log(window.localStorage.getItem('firstTime'));
console.log(typeof window.localStorage.getItem('firstTime'));
console.log(typeof window.localStorage.getItem('firstTime') === 'undefined');

在 Javascript 控制台中可以看到以下内容:

First time?
null
object
false

此外,Storage.getItem() 的 Mozilla 文档说,当请求不存在的密钥时,它会返回“null”

退货

一个包含键值的 DOMString。如果键不存在,则返回 null。

因此,为了完成这项工作,我需要使用以下代码:

document.addEventListener('deviceready', function()
{
    if (window.localStorage.getItem('firstTime') == null)
    {
        // Execute some code for the installation
        // ...

        window.localStorage.setItem('firstTime', 0);
    }
});
于 2016-02-23T00:25:51.773 回答