2016-06-22 6 views
-1

このコードは見ましたが、正しく実行できません。iOSのプログラムでjQueryとJavaScriptをHTMLに挿入する

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    _webview.delegate = self; 
    [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] 
                     pathForResource:@"Samplehtml" ofType:@"html"]isDirectory:NO]]]; 
} 

- (void)webViewDidFinishLoad:(UIWebView *)webView { 
    NSString *jsFile = @"jquery-1.11.0"; 
    NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:jsFile ofType:@"js"]; 
    NSURL *jsURL = [NSURL fileURLWithPath:jsFilePath]; 
    NSString *javascriptCode = [NSString stringWithContentsOfFile:jsURL.path encoding:NSUTF8StringEncoding error:nil]; 
    [_webview stringByEvaluatingJavaScriptFromString:javascriptCode]; 
} 

これは私が試していることです。

MyJavaScript.js

$("p").click(function() { 
alert("hello"); 

})

Samplehtml.html

<!DOCTYPE html> 

<h1>My First Heading</h1> 

    <p>My first paragraph.</p> 

</body> 

+0

エラーが発生していますか?ファイルパスを取得しているかどうかを確認してください。 –

+0

はい私はjsFileのパスを取得しています。私は自分のhtmlページを開いているときにこのjsがどのように動作するのか知りたい。 htmlを開くために使用しているコードは、NSString * htmlFile = [[NSBundle mainBundle] pathForResource:@ "sample" ofType:@ "html"]です。 NSString * htmlString = [NSString stringWithContentsOfFile:htmlファイルのエンコード:NSUTF8StringEncodingエラー:nil]; [webView loadHTMLString:htmlString baseURL:[[NSBundle mainBundle] bundleURL]]; –

+0

私はこのファイル 'jsFile'について話しています –

答えて

1

このようにコードを変更します。

-(void)viewDidLoad { 
    [super viewDidLoad]; 
    self.webView.delegate = self; 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Samplehtml" ofType:@"html"]; 
    NSString *htmlContent = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; 
    [self.webView loadHTMLString:htmlContent baseURL:[NSURL URLWithString:@""]]; 
} 

その後、あなたのwebViewDidFinishLoad

- (void)webViewDidFinishLoad:(UIWebView *)webView { 
    NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:@"simple" ofType:@"js"]; 
    NSURL *jsURL = [NSURL fileURLWithPath:jsFilePath]; 
    NSString *javascriptCode1 = [NSString stringWithContentsOfFile:jsFilePath encoding:NSUTF8StringEncoding error:nil]; 
    jsFilePath = [[NSBundle mainBundle] pathForResource:@"simple2" ofType:@"js"]; 
    jsURL = [NSURL fileURLWithPath:jsFilePath]; 
    NSString *javascriptCode2 = [NSString stringWithContentsOfFile:jsFilePath encoding:NSUTF8StringEncoding error:nil]; 
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"%@\n%@",javascriptCode1, javascriptCode2]]; 
} 

の内側には、これはあなたを助けることを願っています私の側に取り組んでいます。

+0

1つまたは2つの 'js'ファイルがありますか? –

+0

私は2つのjsファイルを持っています。jquery用のものと警告用のものがあります。 –

+0

次に、ファイルの内容を両方とも単一文字列 –

関連する問題