Javascript 使用jQuery在UIWebView上出错
我正在构建一个ePub阅读器,并在UIWebView上加载每个章节的html文件。当用户到达一章的末尾时,我将在同一webView上加载下一章。由于我需要执行一些jQuery函数来创建亮点、注释和许多额外的内容,因此我还将jQuery库注入到查看器中。这是我正在使用的代码:Javascript 使用jQuery在UIWebView上出错,javascript,jquery,ios,uiwebview,Javascript,Jquery,Ios,Uiwebview,我正在构建一个ePub阅读器,并在UIWebView上加载每个章节的html文件。当用户到达一章的末尾时,我将在同一webView上加载下一章。由于我需要执行一些jQuery函数来创建亮点、注释和许多额外的内容,因此我还将jQuery库注入到查看器中。这是我正在使用的代码: - (void)loadBook{ ... [self.bookWebView loadRequest:[NSURLRequest requestWithURL:chapterURL]]; NS
- (void)loadBook{
...
[self.bookWebView loadRequest:[NSURLRequest requestWithURL:chapterURL]];
NSString *jQuery = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"jquery" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil];
[self.bookWebView stringByEvaluatingJavaScriptFromString:jQuery];
}
当它加载第一章时,当调用webviewdiffinishload:
时,$(document).ready
函数被调用,我所有的jQuery代码都能正常工作。当我切换到下一章时,loadBook
函数将使用新的URL再次调用,但这次是$(document)。ready
未被调用,因此当我尝试调用任何函数时,会出现以下错误:ReferenceError:找不到变量:$
为什么在我第一次打电话后它不加载jQuery库?我今天遇到了这个问题,苹果的文档没有用在我的例子中,我是从本地HTML、JS和CSS文件加载的,而不是从远程网址加载的。因此,这可能不适合您,但适用于本地文件 下面是一个变通方法。代码是用Swift写的 方法:
class MyView: ..., UIWebViewDelegate {
var theCounter = 0
...
func myFunctionWhereILoadTheData() {
... load the data (the code in your question)
theCounter += 1
}
...
func webView(webView: UIWebView!, shouldStartLoadWithRequest
request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
switch navigationType {
...
.Other:
if theCounter > 1: return false
}
}
class MyView: ..., UIWebViewDelegate {
var theCounter = 0
...
func myFunctionWhereILoadTheData() {
... load the data (the code in your question)
theCounter += 1
}
...
func webView(webView: UIWebView!, shouldStartLoadWithRequest
request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
switch navigationType {
...
.Other:
if theCounter > 1: return false
}
}