查找用户已选择的输入字段的输入elementID

时间:2013-05-20 22:34:34

标签: javascript ios uiwebview

我有UIWebView并已从服务器加载了文档。 Web文档有几个文本输入字段。如何确定用户触摸的字段的ID或名称 - 已选中。然后我想分配一个值来填充输入字段。

我已经读过足以相信我需要JavaScript但不知道如何将它与Xcode中的目标c相关联。任何帮助将不胜感激。

由于 罗恩

1 个答案:

答案 0 :(得分:0)

以下是一个简单实现的快速示例,可以帮助您入门。

example.html的

<script type="text/javacript">
    function populateField(fieldId, fieldText) {
        $('#' + fieldId).val(fieldText);
    }

    var bridgeScheme = 'myapp';
    (function($) {
        $('#my-textfield').on('focus', function() {
            var data = {
                'action': 'focus',
                'field-id': $(this).attr('id')
            };
            var encodedData = encodeURIComponent(JSON.stringify(data));

            $('#iframe').attr('src', bridgeScheme + encodedData);
        });
    })(jQuery)
</script>

<form id="my-form">
    <div>
        <input type="text" id="my-textfield">
    </div>
</form>

<iframe src="" id="iframe"></iframe>

一些事情:

  • iframe用于生成将通过的请求 UIWebView。我们将能够通过实施来捕捉它 控制器中的UIWebViewDelegate(见后)
  • bridgeScheme变量是您能够检测到请求来自您自己的javascript代码的方式(见后)
  • 将从本机端调用populateField javascript函数,以使用您想要的任何值填充文本字段

ExampleViewController.m

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
  // This needs to be the same value as used in the javascript
  NSString *bridgeScheme = @"myapp";

  // That's where we capture the request if the request's scheme matches
  if ([request.URL.scheme isEqualToString:bridgeScheme])
  {
    // Extract the part of the request url that contains the data we need
    NSString *dataString = [request.URL.absoluteString substringFromIndex:bridgeScheme.length + 1];
    // The data was URL encoded
    dataString = [dataString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    // Here we transform the JSON string into a JSON object (dictionary)
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    // Extract the field id from the dictionary
    NSString *fieldId = dataDictionary[@"field-id"];

    // Call the javascript method on the webview
    NSString *populateFieldJS = [NSString stringWithFormat:@"populateField('%@', '%@')", fieldId, @"Whatever text you want to put in there"];
    [webView stringByEvaluatingJavaScriptFromString:populateFieldJS];

    return NO;
  }

  return YES;
}

希望它有所帮助!