2

我正在尝试让设备就绪事件在 phonegap 3 helloworld 默认应用程序上工作。

html

<html>
<head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <title>Hello World</title>
</head>
<body>
    <div class="app">
        <h1>PhoneGap</h1>
        <div id="deviceready" class="blink">
            <p class="event listening">Connecting to Device</p>
            <p class="event received">Device is Ready</p>
        </div>
    </div>
    <script type="text/javascript" src="phonegap.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript">
        app.initialize();
    </script>
</body>

javascript

var app = {
// Application Constructor
initialize: function() {
    this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
    document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
    app.receivedEvent('deviceready');
    alert('welcome!');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
    var parentElement = document.getElementById(id);
    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');

    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');

    console.log('Received Event: ' + id);
}
};

此代码可以正常工作,并且会在我打开应用程序时触发我的欢迎警报。但是,如果我注释掉任何一行:

<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>

欢迎警报将不再触发。这里发生了什么我不知道 phonegap 使用什么机制来创建这种行为?

4

1 回答 1

3

这里的问题不在于phonegap,而在于receivedEvent导致错误的功能。如果将alert调用之前的 移至receivedEvent,您应该会看到该deviceready事件仍被正确触发。

实际问题是那条线

var listeningElement = parentElement.querySelector('.listening');

<p class="event listening">..</p>从 DOM 中获取元素。由于您删除了该元素,因此listeningElement将是null. 现在打电话

listeningElement.setAttribute('style', 'display:none;');

会因此而失败。

于 2013-09-05T08:35:48.107 回答