我正在尝试将设备就绪事件用于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用什么机制来创建这种行为?
答案 0 :(得分:2)
这里的问题不在于phonegap,而是导致错误的receivedEvent
函数。如果您在致电alert
之前移动receivedEvent
,则应该会看到deviceready
事件仍然正常启动。
实际问题是该行
var listeningElement = parentElement.querySelector('.listening');
从DOM中获取<p class="event listening">..</p>
元素。由于您删除了该元素,listeningElement
将为null
。现在来电
listeningElement.setAttribute('style', 'display:none;');
因此而失败。