【发布时间】:2011-01-18 05:19:53
【问题描述】:
我正在尝试对 UIWebView 中的内容执行一些 Javascript。也许我对 Javascript 运行时的了解不够,但是我对以下示例感到困惑。有关详细信息,请参阅源代码和 cmets:
NSString *html = [NSString stringWithFormat:@"<html><head><script type='text/javascript'>var content='the initial content';function myFunc(){return 'value of content: ' + content;}myFunc();</script></head><body>Hello blank</body></html>"];
// I would expect after this call that the variable content exists, as well as the function myFunc()
[self.webView loadHTMLString:html baseURL:nil];
// However, it appears not to. The following call returns nothing
NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:@"myFunc();"];
NSLog(@"result: %@", result);
// Inserting the Javascript at this point seems to work as expected
result = [self.webView stringByEvaluatingJavaScriptFromString:@"var content='the new content';function myFunc(){return 'value of content: ' + content;}myFunc();"];
NSLog(@"result: %@", result);
// And calling myFunc() at this point is successful
result = [self.webView stringByEvaluatingJavaScriptFromString:@"myFunc();"];
NSLog(@"result: %@", result);
总之,我希望我在加载 html 时创建的 Javascript 全局变量和函数可用于以后的 javascript 调用。令人惊讶的是,它似乎没有,所有的 javascript 东西都必须在以后添加。这是正确的吗?
提前感谢您的帮助。
----- 更新 ----- 在这种情况下,我应该添加 self.view 是一个 WebView。另外,我尝试将脚本标记放在 HTML 文档的头部和正文中,而行为没有改变。
【问题讨论】:
-
这也让我感到惊讶。我不得不问(与问题无关),为什么在声明后调用myFunc()?
-
啊,这只是为了测试是否发生了什么。它不应该在那里。把它拿出来没有任何作用。
标签: javascript iphone cocoa-touch uikit uiwebview