由于iPad屏幕大,很适合利用UIWebView来展示html数据,这样对于开发很会很便利。但也附加的带来了相应的难题,比如:想获取webView中控件的输入数据等。由于项目需要,所以我学习了这部分内容,在此分享自己的经验, 让后来人不必走更多弯路。
话入正题:
首先要载入一个UIWebView,如代码:
- (void)viewDidLoad
{
[superviewDidLoad];
NSString *path = [[NSBundlemainBundle] pathForResource:@"HtmlTest"ofType:@"html"];
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
webView.delegate = self;
//webView载入一个本地的html数据,当然也可以从一个url载入webView
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath: path]]];
[self.view addSubview:webView];
}
然后在webView的载入完成委托方法里
- (void)webViewDidFinishLoad:(UIWebView *)awebView {
NSString *string = [awebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('field_2').value;" ];
NSLog(@"string:%@", string);
//这样就得到了field_2控件的value.
}
当然不必非要在- (void)webViewDidFinishLoad:(UIWebView *)awebView中抓取field_2控件的value,但抓取控件value的时候必须保证webView已经webViewDidFinishLoad,否则抓取不到value的。
抓取可以输入的控件value的方法同上,都是要在webView已经webViewDidFinishLoad之后,在input控件中输入值,然后
NSString *string = [awebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('field_2').value;" ];
这样抓取就可以了。
参考链接:http://hi.baidu.com/qmiao128/blog/item/61f4d1dda0f392285882ddcf.html
示例html:
function fn() {
alert("---------------");
window.locate = '/Custom_Lint/
var url = http://www.hao123.com;
iPhone.downloadUrl(url);'
}
function sayHello() {
objc_msgsend('sayHello');
}
function sayMessageInputValue() {
objc_msgsend( 'say', val( 'message' ) );
}
function sayMessageInputValueWithTitle() {
objc_msgsend( 'say', val( 'multi-arg-message' ), 'withTitle', val( 'title' ) );
}
function val( elementId ) {
return document.getElementById( elementId ).value
}
//@importurl("layout.css");
//body {
background-color: #F2F5A9;
//}
转载请保留,原文链接:http://write.blog.csdn.net/postedit/8650412
若发现有不合适或错误之处,还请批评指正,不胜感激。