下面实现: 在iOS中,实现HTML中的button点击方法。
//每次加载网页请求都会走该方法
- (void)webViewDidFinishLoad:(UIWebView *)webView{
#pragma mark ------ JSContext(OC点击方法实现)
//将context与HTML文件关联起来
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//log为网页中button的onClick方法
context[@"log"] = ^(){
NSLog(@"ssss");
};
}
在viewDidLoad方法中,加载网页文件
UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
[self.view addSubview:web];
web.delegate = self;
NSString *bundle = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
NSString *str = [NSString stringWithContentsOfFile:bundle encoding:NSUTF8StringEncoding error:nil];
[web loadHTMLString:str baseURL:nil];
HTML文件index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="button" value="success" onclick="log()" />
</body>
<!-- //<script>-->
<!-- function log(){-->
<!-- console.log(1);-->
<!-- }-->
<!-- </script>-->
</html>
网友评论