我正在尝试让设备就绪事件在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 使用什么机制来创建这种行为?
最佳答案
这里的问题不在于phonegap,而在于receivedEvent
函数导致错误。如果您移动alert
在调用 receivedEvent
之前,您应该看到 deviceready
事件仍然可以正确触发。
实际的问题是那一行
var listeningElement = parentElement.querySelector('.listening');
获取<p class="event listening">..</p>
来自 DOM 的元素。由于您删除了该元素,listeningElement
将是null
。现在通话
listeningElement.setAttribute('style', 'display:none;');
因此会失败。
关于cordova - 奇怪的phonegap设备就绪事件行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18627589/