问题
I've an UIWebView where a mobile web form URL is loaded. In a method in my application, I would like to insert some text into the HTML text field in the UIWebView which has focus.
How can I do that? Is there a way to get the ID of the HTML element which has focus -- than I can insert the text into this element using JavaScript?
回答1:
The sole way you have to affect the page loaded into the UIWebView
is -stringByEvaluatingJavaScriptFromString:. The least troublesome way would probably be to set up a function in your page that you can call with the text you want in the field. Then pass in a string that is the call to that function, like:
NSString* js = [NSString stringWithFormat:@"myFunction('%@')", someTextVariable];
NSString* results = [self.someWebView stringByEvaluatingJavaScriptFromString:js];
(Escaping any single quotes in someTextVariable
would also be necessary!)
回答2:
This turns out being a JavaScript question, as my solution was to use the jQuery call $("*:focus")
to change the value of the selected element in the UIWebView. This obviously requires that the page loaded in the UIWebView is using jQuery. The call was made using -stringByEvaluatingJavaScriptFromString:
as Sixten Otto describes.
来源:https://stackoverflow.com/questions/9565320/uiwebview-how-to-insert-text-in-a-html-text-field