Javascript javascrip-回调中无法识别的函数
我正在用JQuery开发Cordova应用程序 在我的index.js中,我有以下代码:Javascript javascrip-回调中无法识别的函数,javascript,jquery,Javascript,Jquery,我正在用JQuery开发Cordova应用程序 在我的index.js中,我有以下代码: $(document).ready(function() { console.log("ready"); // Initialize the app app.initialize(); }); // Define the app var app = { // Initialize the app initialize: function() {
$(document).ready(function() {
console.log("ready");
// Initialize the app
app.initialize();
});
// Define the app
var app = {
// Initialize the app
initialize: function() {
// deviceready Event Handler
$(document).on('deviceready', function() {
console.log("Device is ready!");
// 'deviceready' is an DOM element on the Html page.
this.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;');
},
...
}
当我在Cordova中运行脚本时,它抛出了一个错误:
TypeError: this.receivedEvent is not a function
“this”对象似乎没有被正确地引用为app。因为
this
在deviceready
处理程序函数中是不同的。使用箭头功能:
$(document).on("deviceready", () => {...});
或者只是避免在函数中初始化事件侦听器-最好在脚本顶部一次初始化所有事件侦听器。您也可以执行以下操作
initialize: function() {
// deviceready Event Handler
var self = this
$(document).on('deviceready', function() {
console.log("Device is ready!");
// 'deviceready' is an DOM element on the Html page.
self.receivedEvent('deviceready');
});
},
$(文档)中的此
。打开(..
将指向窗口
对象,而不是应用程序
。谢谢,这是有效的。只是想知道为什么箭头函数可以工作?因为箭头函数继承了它的这个
绑定,与普通函数不同。嗨@Jack。很抱歉,我会接受你的答案,因为答案是正确的。但是,刚刚实现了箭头函数在Android上运行emulator时,tion在Cordova中不起作用。但它首先在浏览器环境中起作用。请详细说明如何将设备就绪逻辑移动到JQuery document onReady函数中?