我需要用存储在 objective-c 中的变量填充 html webview。
我相信我需要使用:
[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"John", firstName];
但不确定要放什么以及我的 javascript 需要什么来实现传递的变量。
这里有一些我的 html 可以帮助你理解:
<ul><li><span>First Name:</span> first name needs to go here</li>
<li><span>Last Name:</span> last name needs to go here</li>
更新后的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"idcard" ofType:@"html"]isDirectory:NO]]];
}
-(void)viewDidAppear:(BOOL)animated
{
NSString *str = @"John";
NSString *script = [NSString stringWithFormat:@"myFunc('%@')", str];
[self.webView stringByEvaluatingJavaScriptFromString:script];
}
更新 2: javascript/html:
<ul><li><span>Policy Number:</span>
<script> function myFunc(str)
{
document.write(str) }
</script>
最佳答案
我最终使用了不同的 js 方法并使用了,希望这对某人有帮助。
对象c:
NSString *str = @"John";
NSString *script = [NSString stringWithFormat:@"document.getElementById('name').innerHTML = '%@';", str];
[self.webView stringByEvaluatingJavaScriptFromString:script];
js:
<li><span>Name:</span> <span id = 'name'>name goes here</span>
</li>
关于javascript - ios使用javascript使用 objective-c 的值填充webview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16739212/