在UIWebView的Objective-c中注入JQuery函数

Injecting JQuery function in Objective-c in UIWebView

本文关键字:注入 JQuery 函数 Objective-c UIWebView      更新时间:2023-09-26

我在 jquery 中有这个函数保存为 doc2.js在我的目标中,我的捆绑资源中有副本如下:

文档2.js:

  $(document).ready(function(){
  $(".flip").click(function(){
  $(".panel").slideToggle("slow");
     });
       });

在我的Xcode中,我有以下内容:

 UIWebView * webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
 [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"new" ofType:@"html"]isDirectory:NO]]];
 webView.delegate=self;
 [self.view addSubview:webView];

而这个方法:

-(void)webViewDidFinishLoad:(UIWebView *)webView {
 NSString *jqueryCDN = @"http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
 NSData *jquery = [NSData dataWithContentsOfURL:[NSURL URLWithString:jqueryCDN]];
 NSString *jqueryString = [[NSMutableString alloc] initWithData:jquery encoding:NSUTF8StringEncoding];
 [webView stringByEvaluatingJavaScriptFromString:jqueryString];
 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"doc2" ofType:@"js" inDirectory:NO];
 NSData *fileData = [NSData dataWithContentsOfFile:filePath];
 NSString *jsString = [[NSMutableString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
 [webView stringByEvaluatingJavaScriptFromString:jsString];}

在我的 html 文件中:

<!DOCTYPE html>
 <html>
    <head>        
         <script type="text/javascript" src="jquery.js"></script>
         <style type="text/css"> 
             div.panel,p.flip
            {
                 margin:0px;
                 padding:5px;
                 text-align:center;
                 background:#e5eecc;
                 border:solid 1px #c3c3c3;
             }
             div.panel
             {
                 height:120px;
                 display:none;
             }
             </style>
     </head>
     <body>    
         <div class="panel">
            <p>Any Thing.</p>
            <p>Any Thing.</p>
         </div>        
         <p class="flip">Show/Hide Panel</p>
            </body>
 </html>

这段代码应该处理UIWebView,但它对我不起作用我认为我的jQuery函数没有完成或类似的东西知道吗??

您可能想尝试不同的方法:包含本地副本或从 cdn 下载 jquery。两者兼而有之似乎没有必要。

此外:只需在 doc2.js 中定义一个 javascript 函数,将文件包含在 HTML 中并直接在 Cocoa 中调用它。确保你向可可公开了你的函数

isSelectorExcludedFromWebScript

可以通过以下方式拨打电话

evaluateWebScript