将html注入UIWebVeiw

时间:2011-12-17 05:25:53

标签: javascript dom uiwebview

我有一个UIWebView,我试图将一些html代码注入其中。我有一个首先加载的模板文件,然后我想通过它们的ID来改变元素的内容。

以下是我的代码webViewDidFinishLoad:

    NSString *injectDetails = [NSString stringWithFormat:
                         @"document.getElementById('details').innerHTML = \"%@\";", searchResult.details];
    [webView stringByEvaluatingJavaScriptFromString:injectDetails];

我通过转义引号尝试了它,但也没有用:

    NSString *injectDetails = [NSString stringWithFormat:
                         @"document.getElementById('details').innerHTML = \"%@\";", [searchResult.details stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]];
    [webView stringByEvaluatingJavaScriptFromString:injectDetails];

我出租车注入纯文本,它的工作原理。不起作用的html是一个冗长的字符串,我原来只是使用[webView loadHTMLString:aDescription baseURL:NULL];加载它很好。

我需要做什么才能使用html?

2 个答案:

答案 0 :(得分:0)

我在尝试向文档头添加样式时遇到了同样的问题。所以我刚刚使用\\“(在脚本中看起来像\”)转义了所有双引号。请参阅以下代码:

NSString *js = @" <style type=\\\"text/css\\\"> * { -webkit-touch-callout: none; -webkit-user-select: none; } </style> ";
[_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.head.innerHTML = document.head.innerHTML+\"%@\"",js]];

答案 1 :(得分:-1)

尝试以下代码行来实现此目的。

NSString *imagePath = [[NSBundle mainBundle] resourcePath];
imagePath = [imagePath stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
imagePath = [imagePath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

NSString *HTMLData = @"Hello this is a test<img src="sample.jpg" alt="" width="100" height="100" />";

[webView loadHTMLString:HTMLData baseURL:[NSURL URLWithString: [NSString stringWithFormat:@"file:/%@//",imagePath]]];

第1行  这将获得主束根文件夹的路径。

第2行 我们需要双斜线才能在UIWebView中正常工作,因此我们搜索“/”的所有实例并将其替换为“//”

第3行 与上述相同但我们正在搜索空格并将其替换为等效于%20的HTML

第4行 这是将一些样本数据放在一起用于UIWebView,您将看到我们已将图像源设置为我们的“sample.jpg”文件,因为它位于根文件夹中,如果它位于名为“images”的文件夹中需要将源设置为“images // sample.jpg”。记住双重削减!

第5行 这与我在教程中的示例几乎相同,尽管我们将baseURL设置为应用程序包的根目录,这允许我们相对而不是绝对路径引用所有内容。

使用上述方法,您可以这样做..如果出现任何问题,请告诉我..