一、运行的效果图
1、刚开始的效果
2、运行结束后的效果
二、准备工作
1、准备一个html文件导入到oc工程中
2、jiaohu.html文件的原始内容
3、从oc语言中操作.html文件---增删改查
1).查询操作
var p = document.getElementById('word');
2).删除操作
NSString*html =@"var p = document.getElementById('word');";
NSString*html2 =@"p.remove();";
[webViewstringByEvaluatingJavaScriptFromString:html];
[webViewstringByEvaluatingJavaScriptFromString:html2];
3).更改操作
NSString*htmlUpdate =@"var change = document.getElementsByClassName('change')[0];"
"change.innerHTML = '更改后的值';";
[webViewstringByEvaluatingJavaScriptFromString:htmlUpdate];
4).插入操作
//插入操作1
//插入操作2
NSString*htmlInsert =@"var img = document.createElement('img');"
"img.src = 'img11.jpg';"
"img.width = '200';"
"img.height = '200';"
"document.body.appendChild(img);";
[webViewstringByEvaluatingJavaScriptFromString:htmlInsert];
三、原始代码
#import"ViewController.h"
@interfaceViewController()
@property(nonatomic,strong)UIWebView*webView;
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
/**
*加载本地的html5资源
*/
CGFloatx =60;
CGFloaty =60;
CGFloatwidth =self.view.bounds.size.width;
CGFloatheight =self.view.bounds.size.height;
self.title=@"js oc";
self.webView= [[UIWebViewalloc]initWithFrame:CGRectMake(x, y, width, height)];
//遵守UIWebViewDelegate的代理方法
self.webView.delegate=self;
//加载html的第一种方法
NSURL*url = [[NSBundlemainBundle]URLForResource:@"jiaohu"withExtension:@"html"];
NSURLRequest*request = [NSURLRequestrequestWithURL:url];
[self.webViewloadRequest:request];
[self.viewaddSubview:self.webView];
//加载html的第二种方法
// NSString *path = [[[NSBundle mainBundle] bundlePath]stringByAppendingPathComponent:@"jiaohu.html"];
// NSURL *url = [[NSURL alloc]initWithString:path];
// NSURLRequest *request = [NSURLRequest requestWithURL:url];
// [self.webView loadRequest:request];
// [self.view addSubview:self.webView];
}
#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView*)webView{
//删除操作
NSString*html =@"var p = document.getElementById('word');";
NSString*html2 =@"p.remove();";
[webViewstringByEvaluatingJavaScriptFromString:html];
[webViewstringByEvaluatingJavaScriptFromString:html2];
//更改操作
NSString*htmlUpdate =@"var change = document.getElementsByClassName('change')[0];"
"change.innerHTML = '更改后的值';";
[webViewstringByEvaluatingJavaScriptFromString:htmlUpdate];
//插入操作
}
@end