onDeviceReady没有在PhoneGap hello world app中触发

Oma*_*mar 1 javascript javascript-events cordova

我正在尝试做一个简单的警报('测试')应用程序,但事件没有被解雇,这是代码:

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

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

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>
Run Code Online (Sandbox Code Playgroud)

为什么是这样?

Daw*_*don 6

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

例:

HTML:

<body onload="onLoad">
Run Code Online (Sandbox Code Playgroud)

JS:

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

function onDeviceReady() {
   //anything you want done after deviceready has fired
}
Run Code Online (Sandbox Code Playgroud)

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

例:

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

function onDeviceReady() {
   //anything you want done after deviceready has fired
}
Run Code Online (Sandbox Code Playgroud)