我坚持让一些非常基本的 JS 在我的 UIWebView 中运行。在 WebView 的委托(delegate)中,我有:
- (void)webViewDidFinishLoad:(UIWebView *)wView {
NSString *someHTML = [wView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('box')[0]"];
NSString *allHTML = [wView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
NSLog(@"someHTML: %@", someHTML);
NSLog(@"allHTML: %@", allHTML);
}
但是当调用该方法时,someHTML 为 nil,而 allHTML 包含 webview 中的整个 HTML 主体。
我在 Safari JS 控制台中运行了 JS,它工作得很好(它找到了类 'box' 的 div,所以我知道它在 HTML 中)
有什么建议吗?
更多信息:
FWIW,以下每一项的结果也是零
NSString *result = [self.webView stringByEvaluatingJavaScriptFromString: @"document"];
NSLog (@"1. result: %@", result); //should log the document object?
result = [self.webView stringByEvaluatingJavaScriptFromString: @"document.body"];
NSLog (@"2. result: %@", result); //should log the document body
result = [self.webView stringByEvaluatingJavaScriptFromString: @"document.body.getElementsByClassName"];
NSLog (@"3. result: %@", result); //should log a function
result = [self.webView stringByEvaluatingJavaScriptFromString: @"document.body.getElementsByClassName('box')[0]"];
NSLog (@"4. result: %@", result); //should log the node
最佳答案
改变
NSString *someHTML = [wView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('box')[0]"];
到
NSString *someHTML = [wView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('box')[0].innerHTML;"];
(添加了 .innerHTML)
改变世界。 . .
关于javascript - UIWebView stringByEvaluatingJavaScriptFromString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4560576/