可以Ajax仅加载< page/>而不是HTML文档的所有内容? [英] Possible to ajax load only the <page/> instead of everything of an HTML document?

查看:65
本文介绍了可以Ajax仅加载< page/>而不是HTML文档的所有内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要

  1. 在页面a上,单击指向页面b的链接时,ajax会注入页面b的,而不刷新整个页面
  2. 现在在页面b上,按某个重新加载按钮将刷新整个页面,并运行一些js
  3. js的加载不得超过一次


方法X)是标准方法,它满足1,2,但不满足3.单击指向页面b的链接后,将看到警报.


Method X) is the standard way, which satisfies 1,2 but not 3. Alert is seen after clicking the link to page b.

a.html
<before_page>
  <script>alert('abc')</script>
</before_page>
<page>
  <a href=b.html>b</a>
</page>
<after_page/>

-

b.html
<before_page>
  <script>alert('abc')</script>
</before_page>
<page/>
<after_page/>


方法Y)满足1,3,但不满足2.


Method Y) satisfies 1,3 but not 2.

a.html
<before_page>
  <script>alert('abc')</script>
</before_page>
<page>
  <a href=c.html>c</a>
</page>
<after_page/>

-

c.html
<!--nothing before <page/> -->
<page/>
<!-- nothing after <page/>  -->


问题是如何满足所有1,2,3?


The question is how to satisfy all 1,2,3?

推荐答案

满足所有情况的简便方法是缓存外部页面并将代码放置在每个页面的div中. 缓存页面有两种方法,一种是对每个页面使用data属性,或者在全局范围内启用它.

Easy option to satisfy all scenarios is to cache external pages and place code inside each page's div. There are two ways to cache pages, either using data attribute for each page, or enable it globally.

  • data属性:

<div data-role="page" data-cache-dom="true" id="pageID">
  <!-- JS code / libraries -->
</div>

  • 全球

  • Globally

    <script src="jquery.js"></script>
    <script>
      $(document).on("mobileinit", function () {
        $.mobile.page.prototype.options.domCache = true;
     });
    </script>
    <script src="jquery-mobile.js"></script>
    

  • 如果您不想缓存页面,则可以使用另一种选择,最好将所有JS库,代码和样式表放在每个页面的开头.它们将仅加载一次.一旦隐藏,外部页面将被删除,将代码放入div页将一次又一次加载相同的代码.

    Another option in case you don't want to cache pages, it is preferable to place all JS libraries, code and style sheets in head of each and every page. They will be loaded once only. External pages are removed once hidden, placing code in page div will load same code again and again.

    $(document).on("pagecreate", "#pageID", function () {
      $(".selector").on("event", function () {
        /* code */
      });
    });
    

    演示

    Demo

    这篇关于可以Ajax仅加载&lt; page/&gt;而不是HTML文档的所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆