已經看到了這段代碼,但我無法正確運行它。在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>
您是否收到任何錯誤?檢查你是否獲得文件路徑? –
是的,我得到了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]]; –
我在說'jsFile'這個文件 –