我运行Cordova示例项目并想测试Cordova API,但是,即使cordova.js嵌入index.html,似乎也无法使用API。这是代码
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
notification.all();
</script>
在index.js中:
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 evheyent. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// 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;');
alert('Received Event: ' + id);
}
};
var notification={
all:function (){alert(navigator.connection.type);}
}
错误是&#34;无法读取属性&#39;键入&#39;未定义&#34;
答案 0 :(得分:1)
由于您在我的其他答案之后发布了您的代码,而不是更改我以前的帖子,我正在写一个新的答案。
Javascript是异步的,因此在执行app.initialize()调用时,也会在触发deviceready之前执行notification.all()调用。在任何情况下,你的初始化调用只会为deviceready添加监听器,然后你可以在获得deviceready之前调用你的all()函数。