我有一个虚拟 HTML 文件,用于加载我的 javascript 文件,以便我可以使用其中的函数:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript" src="js/makeTable.js"></script>
</head>
<body>
</body>
</html>
我想通过对 UIWebView 使用 stringByEvaluatingJavascriptFromString 函数,在我的 Xcode 代码中使用 makeTable.js 中的函数。我需要传递的所有参数都已正确传递,这是我通过使用 Xcode 中的调试器了解到的。我不知道为什么没有加载 javascript,我尝试使用警报来查看它是否加载。
在 Xcode 中,当我尝试在 viewDidLoad 方法中加载我的 html 文件时,我的代码如下所示
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"loadingWeb"
ofType:@"html"
inDirectory:@"/htdoc" ];
NSString *html = [NSString stringWithContentsOfFile:htmlPath
encoding:NSUTF8StringEncoding
error:nil];
[_webView loadHTMLString:html
baseURL:[NSURL fileURLWithPath:
[NSString stringWithFormat:@"%@/htdoc/",
[[NSBundle mainBundle] bundlePath]]]];
[_webView loadHTMLString:@"<script>alertMeWithMyCustomFunction('I am');</script>" baseURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/htdoc/",[[NSBundle mainBundle] bundlePath]]]];
}
在 UIWebView 中,除了空白屏幕外什么也没有显示。在 makeTable.js 文件中,alertMeWithMyCustomFunction 方法如下所示:
function alertMeWithMyCustomFunction(text) {
alert(text+' -> in lib.js');
}
基本上,我如何使用 javascript 函数并使用 stringByEvaluatingJavascriptFromString 方法从 Xcode 向它们传递参数,因为最后我希望像这行代码这样的东西可以工作:
NSString* script = [NSString stringWithFormat:@"table = makeTable( %d, %@, %@, %@);", i, [albumObj.moments[i] latitude], [albumObj.moments[i] longitude], jpgPath];
[_webView stringByEvaluatingJavaScriptFromString:script];
我想使用的所有 JS 函数都在 makeTable.js 文件中。我只需要能够在 UIWebView 中与这个文件进行交互,因为我所有的数据都在 Xcode 中,但我需要在 JS 中使用它
最佳答案
问题是 loadHTMLString:baseURL:
在添加新的 HTML 之前删除了之前在 UIWebView 中的 HTML。因此,当您在 viewDidLoad
中第二次调用 loadHTMLString:baseURL:
以注入(inject)脚本标签时,它会清除您刚刚从 loadingWeb.html 添加的 HTML。为什么不使用 stringByEvaluatingJavaScriptFromString:
而不是注入(inject)脚本标签?
此外,如果您不知道,您可以使用 Safari 中的网络检查器来检查和调试 UIWebView 中的 HTML/CSS/JS。在使用 UIWebViews 时,这对我来说是一个救星。 引用this answer获取说明。
关于javascript - 如何在 UIWebView 中将数据从 Xcode 传递到 javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24765644/