Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jQuery在UIWebView上出错_Javascript_Jquery_Ios_Uiwebview - Fatal编程技术网

Javascript 使用jQuery在UIWebView上出错

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

我正在构建一个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];
}
当它加载第一章时,当调用
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
  }
}
  • 在UIWebViewDelegate中,创建一个Int变量,该变量将在加载数据时递增
  • 每次加载数据(或发布请求)时,将其增量为1
  • 在shouldStartLoadWithRequest中,检查导航类型是否为“其他”:如果是且计数器变量大于1,则返回false(Objective-C中为否)
  • 这是因为每次显示视图时都会实例化它,因此计数器会重置为0

    代码

    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
      }
    }