gpt4 book ai didi

javascript - iOS 从 UIWebView 检索 javascript 变量

转载 作者:行者123 更新时间:2023-11-28 18:00:22 24 4
gpt4 key购买 nike

我有一个包含 <div> 的 html 文件,我正在加载到 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 中检索这个变量,然后在我的代码中使用它?

谢谢!

最佳答案

UIWebView 方法 stringByEvaluatingJavaScriptFromString: 是 JavaScript 环境的唯一接口(interface)。它计算并返回您传递给它的 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];

关于javascript - iOS 从 UIWebView 检索 javascript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14342609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com