主要用到UIWebView的 – stringByEvaluatingJavaScriptFromString:方法
如图:
上端UINavigationBar里有个Button,绑定selectCity事件
- UIBarButtonItem *selectBtn = [[UIBarButtonItem alloc] initWithTitle:@"Select" style:UIBarButtonItemStyleBordered target:self action:@selector(selectCity)];
- self.navigationItem.rightBarButtonItem = selectBtn;
- [selectBtn release];
- - (void)selectCity
- {
- NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:@"select();"];
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You select city:" message:result delegate:self cancelButtonTitle:@"Sure" otherButtonTitles:@"Cancel", nil];
- [alert show];
- [alert release];
- }
html代码(使用jquery mobile)
- <!DOCTYPE html>
- <html>
- <head>
- <title>city</title>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="stylesheet" href="jquery.mobile-1.0.css"/>
- <script type="text/javascript" src="jquery.js"></script>
- <script type="text/javascript" src="jquery.mobile-1.0.js"></script>
- <script>
- function select()
- {
- var cities = document.getElementsByName("city");
- for(i=0; i<cities.length; i++)
- {
- if(cities.item(i).checked)
- {
- var result = cities.item(i).getAttribute("value");
- return result;
- }
- }
- }
- </script>
- </head>
- <body>
- <div data-role="page">
- <div data-role="content">
- <fieldset data-role="controlgroup">
- <legend>Choose a city:</legend>
- <input type="radio" name="city" id="radio-choice-1" value="广州市" checked="checked" />
- <label for="radio-choice-1">广州市</label>
- <input type="radio" name="city" id="radio-choice-2" value="深圳市" />
- <label for="radio-choice-2">深圳市</label>
- <input type="radio" name="city" id="radio-choice-3" value="珠海市" />
- <label for="radio-choice-3">珠海市</label>
- <input type="radio" name="city" id="radio-choice-4" value="东莞市" />
- <label for="radio-choice-4">东莞市</label>
- <input type="radio" name="city" id="radio-choice-5" value="茂名市" />
- <label for="radio-choice-5">茂名市</label>
- <input type="radio" name="city" id="radio-choice-6" value="湛江市" />
- <label for="radio-choice-6">湛江市</label>
- <input type="radio" name="city" id="radio-choice-7" value="阳江市" />
- <label for="radio-choice-7">阳江市</label>
- <input type="radio" name="city" id="radio-choice-8" value="中山市" />
- <label for="radio-choice-8">中山市</label>
- <input type="radio" name="city" id="radio-choice-9" value="佛山市" />
- <label for="radio-choice-9">佛山市</label>
- <input type="radio" name="city" id="radio-choice-10" value="惠州市" />
- <label for="radio-choice-10">惠州市</label>
- <input type="radio" name="city" id="radio-choice-11" value="梅州市" />
- <label for="radio-choice-11">梅州市</label>
- <input type="radio" name="city" id="radio-choice-12" value="汕头市" />
- <label for="radio-choice-12">汕头市</label>
- </fieldset>
- <a data-role="button" onclick="submit()" data-theme="b">Submit</a>
- </div>
- </div>
- </div>
- </body>
- </html>