2016-06-22 54 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:htmlFile encoding:NSUTF8StringEncoding error: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

你有一個或兩個'js'文件? –

+0

我有兩個js文件。一個用於jquery和其他用於警惕。 –

+0

然後你需要在單個字符串中添加兩個文件的內容 –

相關問題