Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 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 Reply

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...