1

I'm trying to do a simple alert('test') app, but the event isn't being fired, this is the code:

function onLoad() {
    document.addEventListener("deviceready", onDeviceReady, false);
}

// Cordova is loaded and it is now safe to make calls Cordova methods
//
function onDeviceReady() {
    alert('omar');
}

HTML:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Hello World</title>
    </head>
    <body>
        <div class="app">
            <h1>AAAA</h1>
        </div>
        <script type="text/javascript" src="cordova-2.2.0.js"></script>
        <script type="text/javascript" src="js/index.js"></script>

    </body>
</html>

Why is this?

4

4 回答 4

6

正确的方法是在添加事件监听器之前确保文档已经完全加载。

例子:

HTML:

<body onload="onLoad">

JS:

function onLoad() {
    document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady() {
   //anything you want done after deviceready has fired
}

使用 jQuery,您可以$(document).ready()使用<body onload="onLoad()">

例子:

$(document).ready() {
    document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady() {
   //anything you want done after deviceready has fired
}
于 2012-11-09T17:01:23.073 回答
0

这适用于 Cordova 应用程序(在 iOS 和 Android 上测试)和普通网页。不需要库(jQuery)。

// Use onDeviceReady if we run in Cordova
window.addEventListener('load', function(){
    if (window.Cordova) {
        document.addEventListener('DeviceReady', bootstrap, false);
    } else {
        bootstrap();
    }
}, false);

Cordova 文档说DeviceReady事件是这样制作的,不能错过。即使设备之前准备好,也会调用处理程序。

于 2016-02-21T12:14:13.230 回答
0

我宁愿采用异步方法,如下所示:

bindEvents: function () {
    var me = this;

    document.addEventListener('deviceready', function () {
        me.onDeviceReady();
    }, false);

    $(document).ready(function () {
        me.onDocumentReady();
    });
},

documentReady: false,
onDocumentReady: function () {
    this.documentReady = true;
    this.checkReady();
},

deviceReady: false,
onDeviceReady: function () {
    this.deviceReady = true;
    this.checkReady();
},

checkReady: function (id) {
    if (this.documentReady && this.deviceReady) this.load();
},

load: function () {
    // do stuff
}

这样您就不会冒险在事件发生后附加处理程序。

于 2016-01-25T02:46:42.897 回答
-2

放在()末尾onDeviceReady

onDeviceReady()

让我知道这是否正确,在浏览器上测试时它对我有用

于 2016-08-23T08:22:06.293 回答