0

我正在构建一个 ePub 阅读器,并且正在加载 UIWebView 上每一章的 html 文件。当用户到达一章的末尾时,我会在下一章的同一个 webView 上加载。因为我需要执行一些 jQuery 函数来创建高亮、注释和许多额外的内容,所以我还将 jQuery 库注入查看器。这是我正在使用的代码:

- (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];
}

当它加载第一章时,当webViewDidFinishLoad:被调用时,$(document).ready函数被调用并且我所有的 jQuery 代码都能完美运行。当我切换到下一章时,loadBook使用新 URL 再次调用该函数,但这次$(document).ready没有调用,所以当我尝试调用我的任何函数时,我收到以下错误:ReferenceError: Can't find variable: $

为什么在我第一次调用后它没有加载 jQuery 库?

4

1 回答 1

0

I ran into this today and Apple's documentation was to no avail. In my case, I was loading from local HTML, JS, and CSS files--NOT from a remote web address. So, this might not do it for you, but it does work for local files.

The following is a workaround. The code is in Swift.

Method:

  1. In your UIWebViewDelegate, create an Int variable that will be incremented when your data is loaded.
  2. Increment it by 1 each time that you load your data (or post the request)
  3. In shouldStartLoadWithRequest, check whether the navigation type is "Other" or not: if it is and the counter variable is greater than 1, return false (NO in Objective-C).

This works because the view is instantiated each time it is presented, so the counter is reset to 0.

Code:

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
  }
}
于 2014-07-15T21:29:20.823 回答