onDeviceReady没有在PhoneGap hello world app中触发

时间:2012-11-09 16:17:47

标签: javascript cordova javascript-events

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

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>

为什么会这样?

4 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

我宁愿采取异步方法,如下:

$data = $statement->fetchAll(PDO::FETCH_ASSOC); // no fetch group
$final_data = array();
foreach($data as $values) {
    $final_data[$values['category_name']][] = $values['area_name'];
    // assign category as key, push into the array container the area name
}

// then get going on building your desired html markup using the manually grouped `$final_data` below

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

答案 2 :(得分: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事件是这样发生的,不容错过。即使设备在之前就绪,也会调用处理程序。

答案 3 :(得分:-2)

onDeviceReady放在onDeviceReady() 的末尾?

var result =
    (from a in db.A
     where a.Id == IDParameter
     join b in db.B on a.Id equals b.AId into Bs
     select new
     {
         a,
         Bs =
            (from b in Bs
             join c in db.C on b.Id equals c.BId into Cs
             select new
             {
                 b,
                 Cs =
                    (from c in Cs
                     join d in db.D on c.Id equals d.CId into Ds
                     select new
                     {
                         c,
                         Ds = Ds.ToList()
                     }).ToList() 
             }).ToList()
     }).ToList();

如果这是合适的人,请告诉我,在浏览器上进行测试时,它对我有用