如何在ios中从目标c方法传递javascript函数的元素id?

时间:2014-03-21 08:31:01

标签: javascript ios uiwebview

朋友们,我在我的ios应用程序中创建了一个Web视图,我在web视图中也使用了java脚本。我的Web视图显示了一个包含java脚本的本地Web页面。在网页上单击按钮时,它会从脚本中调用一个函数。函数将id作为参数现在我想从我的本机应用程序代码传递该id。我怎么能这样做。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    web.delegate=self;
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
                                                                          pathForResource:@"Untitled" ofType:@"html"]isDirectory:NO]]];

}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
//    if ([[[request URL] absoluteString] hasPrefix:@"ios:"])
//    {
//        
//        // Call the given selector

       [self performSelector:@selector(webToNativeCall)];
        // Cancel the location change
        return YES;
//    }
//    return YES;

}

- (void)webToNativeCall
{

    NSString *theJSMethod = [NSString stringWithFormat:@"getId()"];
    NSString *returnvalue =  [web stringByEvaluatingJavaScriptFromString:theJSMethod];
    NSLog(@"%@",returnvalue);



}


<html>

    <head>
        <title></title>
         <script type='text/javascript'>
            function getText()
            {
                var x=document.getElementById(id).title;
                var z=id;
                alert(id);
                return z;
            }
         function getId(id)
         {
             window.location  = 'ios:webToNativeCall';
             var x=document.getElementById(id).title;
             alert(x);
             return document.getElementById(id).title;;
         }
        function locationChange(id)
        {
            window.location  = 'ios:webToNativeCall';
            var x=id;
            return x
        }
</script>
    </head>
    <body>


    <img id="Image-Maps-Com-image-maps-2014-03-20-025237" src="01.jpg" border="0" width="640" height="782" orgWidth="640" orgHeight="782" usemap="#image-maps-2014-03-20-025237" alt="" />
<map name="image-maps-2014-03-20-025237" id="ImageMapsCom-image-maps-2014-03-20-025237">
    <area id="demo1" shape="rect" coords="54,376,168,477" alt="" title="abc" style="outline:none;" target="_self" href="" onclick="locationChange(this.id)"    />
    <area id="demo2" shape="rect" coords="57,481,171,582" alt="" title="XYZ" style="outline:none;" target="_self" href="" onclick="locationChange(this.id)"    />
</map></map>


    </body>
</html>

1 个答案:

答案 0 :(得分:0)

类似这样的事情

- (void)webToNativeCall
{
NSString * paramId = @"elementId";
    NSString *theJSMethod = [NSString stringWithFormat:@"getId('%@')", paramId];
    NSString *returnvalue =  [web stringByEvaluatingJavaScriptFromString:theJSMethod];
    NSLog(@"%@",returnvalue);
}