下面實(shí)現(xiàn): 在iOS中瓶蝴,實(shí)現(xiàn)HTML中的button點(diǎn)擊方法毒返。
//每次加載網(wǎng)頁請(qǐng)求都會(huì)走該方法
- (void)webViewDidFinishLoad:(UIWebView *)webView{
#pragma mark ------ JSContext(OC點(diǎn)擊方法實(shí)現(xiàn))
//將context與HTML文件關(guān)聯(lián)起來
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//log為網(wǎng)頁中button的onClick方法
context[@"log"] = ^(){
NSLog(@"ssss");
};
}
在viewDidLoad方法中,加載網(wǎng)頁文件
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>