Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

javascript - onDeviceReady not firing in PhoneGap hello world app

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The correct way is to make sure that document has completely loaded before adding the event listener.

Example:

HTML:

<body onload="onLoad">

JS:

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

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

With jQuery you can use $(document).ready() instead of <body onload="onLoad()">

Example:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...