gpt4 book ai didi

JavaScript onDeviceReady 未触发

转载 作者:行者123 更新时间:2023-11-30 00:18:30 27 4
gpt4 key购买 nike

我正在创建我的第一个 Cordova 项目,我是 JavaScript 的新手。

我正在学习一些教程,但现在我正在将一些 JavaScript 代码集成到 index.js 文件中。

根据 Joerg 的回答编辑 index.js:

  // Declaraci—n de variables globales
var myScroll, myScrollMenu, cuerpo, menuprincipal, wrapper, estado;
console.log('ENTRANDO!!!!');

// Guardamos en variables elementos para poder rescatarlos despuŽs sin tener que volver a buscarlos
cuerpo = document.getElementById("cuerpo"),
menuprincipal = document.getElementById("menuprincipal"),
wrapper = document.getElementById("wrapper");

var xhReq = new XMLHttpRequest();

var app = {

// Constructor de la app
initialize: function() {
console.log('ENTRANDO EN VAR APP FUNCTION()!!!');
// Estado inicial mostrando capa cuerpo
estado="cuerpo";

// Creamos el elemento style, lo a–adimos al html y creamos la clase cssClass para aplicarsela al contenedor wrapper
var heightCuerpo=window.innerHeight-46;
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { position:absolute; z-index:2; left:0; top:46px; width:100%; height: '+heightCuerpo+'px; overflow:auto;}';
document.getElementsByTagName('head')[0].appendChild(style);

// A–adimos las clases necesarias
cuerpo.className = 'page center';
menuprincipal.className = 'page center';
wrapper.className = 'cssClass';

// Leemos por ajax el archivos opcion1.html de la carpeta opciones
xhReq.open("GET", "opciones/opcion1.html", false);
xhReq.send(null);
document.getElementById("contenidoCuerpo").innerHTML=xhReq.responseText;

// Leemos por ajax el archivos menu.html de la carpeta opciones
xhReq.open("GET", "opciones/menu.html", false);
xhReq.send(null);
document.getElementById("contenidoMenu").innerHTML=xhReq.responseText;

// Creamos los 2 scroll mediante el plugin iscroll, uno para el menœ principal y otro para el cuerpo
myScroll = new iScroll('wrapper', { hideScrollbar: true });
myScrollMenu = new iScroll('wrapperMenu', { hideScrollbar: true });

this.bindEvents();
},

bindEvents: function() {
$(document).ready(function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
});
},

onDeviceReady: function() {
// Ejecutamos la funci—n FastClick, que es la que nos elimina esos 300ms de espera al hacer click
new FastClick(document.body);
console.log('ENTRANDO EN VAR ONDEVICEREADY!!!');

app.readPosts();


},




readPosts: function() {
posts_url: "http://your.ip.goes.here:3000/posts/";
console.log('Reading posts');
$.ajax({
type: "GET",
dataType: "json",
url: app.posts_url,
success: app.onSuccess,
error: app.onError
});

console.log('Reading posts asynchrounously');
},

onSuccess: function(data) {
var items = [];
$.each(data, function(key, val){
items.push('<a href="' + app.posts_url + val.id + '">' + val.id + ' - ' +val.title + '</a>');
});
$('#posts').html(items.join('<br/>'));
console.log('Exiting onSuccess');
},

onError: function(data, textStatus, errorThrown) {
console.log('Data: ' + data);
console.log('Status: ' + textStatus);
console.log('Error: ' + errorThrown);
$("#posts").html('Error while loading posts');
console.log('Exiting onError');
}

};

// Funci—n para a–adir clases css a elementos
function addClass( classname, element ) {
var cn = element.className;
if( cn.indexOf( classname ) != -1 ) {
return;
}
if( cn != '' ) {
classname = ' '+classname;
}
element.className = cn+classname;
}

// Funci—n para eliminar clases css a elementos
function removeClass( classname, element ) {
var cn = element.className;
var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" );
cn = cn.replace( rxp, '' );
element.className = cn;
}

function menu(opcion){

// Si pulsamos en el bot—n de "menu" entramos en el if
if(opcion=="menu"){
if(estado=="cuerpo"){
cuerpo.className = 'page transition right';
estado="menuprincipal";
}else if(estado=="menuprincipal"){
cuerpo.className = 'page transition center';
estado="cuerpo";
}
// Si pulsamos un bot—n del menu principal entramos en el else
}else{

// A–adimos la clase al li presionado
addClass('li-menu-activo' , document.getElementById("ulMenu").getElementsByTagName("li")[opcion]);

// Recogemos mediante ajax el contenido del html segœn la opci—n clickeada en el menu
xhReq.open("GET", "opciones/opcion"+opcion+".html", false);
xhReq.send(null);
document.getElementById("contenidoCuerpo").innerHTML=xhReq.responseText;

// Refrescamos el elemento iscroll segœn el contenido ya a–adido mediante ajax, y hacemos que se desplace al top
myScroll.refresh();
myScroll.scrollTo(0,0);

// A–adimos las clases necesarias para que la capa cuerpo se mueva al centro de nuestra app y muestre el contenido
cuerpo.className = 'page transition center';
estado="cuerpo";

// Quitamos la clase a–adida al li que hemos presionado
setTimeout(function() {
removeClass('li-menu-activo' , document.getElementById("ulMenu").getElementsByTagName("li")[opcion]);
}, 300);

}



}

我正在插入一些 console.log 行来跟踪执行,但没有启动 onDeviceReady 函数。

请看一下我的代码,告诉我哪里出了问题。

谢谢。

编辑:

控制台日志

ENTRANDO!!!!
index.js:16 ENTRANDO EN VAR APP FUNCTION()!!!
(index):85 cordova :: fired deviceready event!
(index):85 deviceready has not fired after 5 seconds.
(index):85 Channel not fired: onCordovaConnectionReady
(index):85 Channel not fired: onCordovaInfoReady

实现 Joerg 的回答后完成控制台日志:

ENTRANDO!!!!
index.js:16 ENTRANDO EN VAR APP FUNCTION()!!!
index.js:33 Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
cordova.js:633 Uncaught Function required as first argument!forceFunction @ cordova.js:633Channel.subscribe @ cordova.js:645document.addEventListener @ cordova.js:132(anonymous function) @ index.js:51j @ jquery-2.1.4.min.js:2k.fireWith @ jquery-2.1.4.min.js:2n.extend.ready @ jquery-2.1.4.min.js:2I @ jquery-2.1.4.min.js:2
(index):85 Falling back on PROMPT mode since _cordovaNative is missing. Expected for Android 3.2 and lower only.
(index):85 Ripple :: Environment Warming Up (Tea. Earl Gray. Hot.)
ripple.js:50 GET http://192.168.1.78:3000/config.xml 404 (Not Found)(anonymous function) @ ripple.js:50module.exports.initialize @ ripple.js:50_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13(anonymous function) @ ripple.js:38
ripple.js:50 POST http://192.168.1.78:3000/ripple/user-agent 404 (Not Found)(anonymous function) @ ripple.js:50setUserAgent @ ripple.js:39_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13(anonymous function) @ ripple.js:38
(index):85 cordova :: Setting the user agent server side failed.
(index):85 cordova :: Initialization Finished (Make it so.)
index.js:3 ENTRANDO!!!!
index.js:16 ENTRANDO EN VAR APP FUNCTION()!!!
cordova.js:633 Uncaught Function required as first argument!forceFunction @ cordova.js:633Channel.subscribe @ cordova.js:645document.addEventListener @ cordova.js:132(anonymous function) @ index.js:51j @ jquery-2.1.4.min.js:2k.fireWith @ jquery-2.1.4.min.js:2n.extend.ready @ jquery-2.1.4.min.js:2I @ jquery-2.1.4.min.js:2
(index):85 Falling back on PROMPT mode since _cordovaNative is missing. Expected for Android 3.2 and lower only.
(index):85 cordova :: fired deviceready event!
(index):85 deviceready has not fired after 5 seconds.
(index):85 Channel not fired: onCordovaConnectionReady
(index):85 Channel not fired: onCordovaInfoReady
(index):85 deviceready has not fired after 5 seconds.
(index):85 Channel not fired: onCordovaConnectionReady
(index):85 Channel not fired: onCordovaInfoReady

最佳答案

使用 Cordova/Phonegap 时最重要的事件是设备就绪事件。这个事件很特别,来自 cordova 文档:

This event behaves differently from others in that any event handler registered after the event has been fired will have its callback function called immediately.

另一方面,您使用 jQuery,它需要有文档就绪事件。

因此,您需要将它们放在一起并重写您的绑定(bind)函数:

bindEvents: function() {
$(document).ready(function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
});
},

更新:

在 stackoverflow 上有很多关于如何管理事件以及如何组织 cordova 应用程序的主要结构的问题。这是一个基本脚本,您可以使用和扩展它:

/**
* Starts the app by calling the function initialize();
*/

app.initialize();

// The main app starts here, put all your functions inside app!!

var app = {

/**
* If you have global variables, put them here. You call them e. g.: app.myStringVar
* Remember to put a comma at the end of each line!!
*
*/

myStringVar: "Hello",
myBoolVar: true,

/**
* Here is your first function, which is called above.
* Put in this function nothing more then the important event listener, like this one for jQuery AND the Cordova deviceready listener.
*/

initialize: function () {

/**
* First listen to the jQuery ready event, if you use jQuery, and then listen to cordova.
*
* If you use jQuery Mobile, then use:
*
* $(document).on("pageinit", function () {
* document.addEventListener("deviceready", app.onDeviceReady, false);
* });
*/

$(document).ready(function () {
document.addEventListener("deviceready", app.onDeviceReady, false);

/**
* You can put other Cordova listener here, for example the pause or resume listener:
*
* document.addEventListener("pause", app.onPause, false);
* document.addEventListener("resume", app.onResume, false);
*
*
*/
});
},

/**
* If the Cordova deviceready event is fired, this function is called. Put in this function all the basic logic for your app.
*
* Put all your other function below and call them e.g.: app.myFirstFunction();
*/

onDeviceReady: function () {
app.myFirstFunction("Hi, cordova!");
}, myFirstFunction: function (term) {
alert(term);
}
};

关于JavaScript onDeviceReady 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33974156/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com