我正在使用phonegap/cordova 2.1.0框架在IOS中制作一个应用程序。我想从 Objective-C 调用驻留在 index.html 中的 JavaScript 函数。所以,首先我加载index.html,然后尝试调用javascript 函数。我的代码如下:
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"www"];
NSURL *baseURL = [NSURL fileURLWithPath:path];
NSString *myFile = [path stringByAppendingPathComponent:@"index.html"];
//NSLog(@"base url= %@",myFile);
NSData *myFileData = [[NSData alloc] initWithContentsOfFile:myFile];
NSString* myFileHtml = [[NSString alloc] initWithData:myFileData encoding:NSASCIIStringEncoding];
[theWebView loadHTMLString:myFileHtml baseURL:baseURL];
// to call javascript function
[theWebView stringByEvaluatingJavaScriptFromString:@"onDeviceReady()"];
倒数第二行加载index.html,最后一行调用其中的函数。但是,不知何故,上面的代码不起作用。我在语法方面出错了吗?
Alos,既然index.html已经被加载过,那么我如何指定函数所在的文件名(即index.html)而不再次加载它呢?谢谢。
Javascript函数如下:
function onDeviceReady(callback) {
var item = window.localStorage.getItem("key");
var message = "deviceready localStorage.getItem('key')="+item+" localStorage.length="+window.localStorage.length;
if( item == null){
item = "";
}
item = item + "value";
window.localStorage.setItem("key", item);
var value = window.localStorage.getItem("key");
if ( deviceType == 'android' && gAppControl.loadScript == false ){
loadScript('iscroll.js');
gAppControl.loadScript = true;
document.addEventListener("backButton", backPressed, false);
}
var db = window.openDatabase(dbName, "1.0", gAppConfig.dbMessage, 200000);
db.transaction(queryDB, errorCB , callback);
// return
return;
}
最佳答案
onDeviceReady()
这是phonegap的API,如果设备没有准备好,你将无法调用任何Phonegap插件,那么onDeviceReady()函数的细节是什么呢?涉及任何phonegap插件吗?
代码看起来没有问题,这是我的code ,具有与 Objective-C 和 HTML-Javascript 进行通信的桥梁,
关于javascript - 从 Objective-C 调用 javascript 函数的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14151719/