我的html文件包含< div
>并且我正在加载到UIWebView中,我需要知道div中有多少行文本,所以我可以使用javascript检查:
<script>
function countLines() {
var divHeight = document.getElementById('myDiv').offsetHeight;
var lineHeight = parseInt(document.getElementById('myDiv').style.lineHeight);
var lines = divHeight / lineHeight;
alert("Lines: " + lines);
}
</script>
它确实警告变量“lines”
在Objective-C中如何从UIWebView中检索此变量,然后在我的代码中使用它?
三江源!
答案 0 :(得分:8)
UIWebView方法stringByEvaluatingJavaScriptFromString:
是JavaScript环境的唯一接口。它会计算并返回传递给它的JavaScript表达式值的字符串表示形式。所以,例如:
// simplified expression, no function needed
NSString *expr = @"document.getElementById('myDiv').offsetHeight / document.getElementById('myDiv').style.lineHeight";
// now pass it to the web view and parse the result
int lines = [[self.webView stringByEvaluatingJavaScriptFromString:expr] intValue];
答案 1 :(得分:3)
这很简单:
NSString *jsString = @"function countLines() {var divHeight = document.getElementById('myDiv').offsetHeight;var lineHeight = parseInt(document.getElementById('myDiv').style.lineHeight);var lines = divHeight / lineHeight;return lines;};countLines();";
NSString *responseString = [MywebView stringByEvaluatingJavaScriptFromString:jsString];
你应该在responseString变量中有值,你可以从NSString转换为数字: - )