jQuery mobile如何检测刷新

Spr*_*ing 6 html javascript jquery jquery-mobile

一些背景;

默认情况下,当您单击指向单独HTML页面的链接时,JQM会在该页面上加载第一个data-role ="page"并将其附加到第一页的DOM,但事情是JQM只加载该页面div而不是任何脚本等容器外面的等等.

我有一个jQuery移动应用程序有5页"login.html""menu.html""account.html""settings.html"..等

我改变页面的样子;

 $.mobile.changepage("account.html")
Run Code Online (Sandbox Code Playgroud)

另外,我将所有页面加载逻辑放到我的第一页login.html中 ;

<script>
     $(document).on('pageinit', '#loginpage', function() {
       //do some stuff run some ajax scripts and add some html to its body
    });

  $(document).on('pageinit', '#accountpage', function() {
        //do some stuff run some ajax scripts and add some html to its body
    });

   $(document).on('pageinit', '#settingspage', function() {
        //do some stuff run some ajax scripts and add some html to its body
    });

</script>
Run Code Online (Sandbox Code Playgroud)

虽然这个应用程序运行良好,问题是我发现它非常脆弱,很难从意外错误中幸存下来.例如;

由于每个页面的主体html将如何加载在login.html中定义,这意味着如果用户手动刷新任何这些页面的任何时刻,页面将加载而不运行这些脚本并加载没有正文的空页面.在那一刻,因为从内存中删除了正确的DOM,用户被困在一个装满空页的应用程序中,唯一的方法是他足够智能去输入"login.html"到地址栏然后才能启动所有进程顺利.

我想我们不能100%隐藏地址栏,滚动下来后再次可见.

所以这是我提出的一个问题,其他一些奇怪的事情可能会发生,如果不知何故DOM被破坏只能再次使用应用程序的方法是输入login.html地址栏,用户可能不会对此有所了解.

如何让这个应用程序更健壮,比如检测任何DOM损坏或刷新并将用户转发到login.html,这样他就不会陷入使用空页面的应用程序中.

pet*_*erm 2

减轻痛苦的一种方法是将特定于页面的脚本放入 data-role="page"适当的 html 文件中的元素中,并保留该元素外部每个页面都相同的脚本(在 和body/或的 和 处head)。

这样,即使用户刷新页面,所有必要的脚本仍然会被执行。但有一个问题,在绑定任何处理程序之前,您需要先取消绑定它们。否则你最终会附加多个处理程序。

为了说明这一点:

login.html更新):

<div data-role="page" id="loginpage">
    <script>
        $(document).off('pageinit', '#loginpage').on('pageinit', '#loginpage', function() {
            $(document).off('click', '#btnaccount').on('click', '#btnaccount', function(){
                $.mobile.changePage("jqmaccount.html", {reloadPage: true});
            });
            console.log("paginit in loginpage");
        });
        $(document).off('pageshow', '#loginpage').on('pageshow', '#loginpage', function() {
            console.log("pageshow in loginpage");
        });
    </script>
    <div data-role="content">
        <a id="btnaccount" href="#" data-role="button">Account</a>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

account.html更新):

<div data-role="page" id="accountpage">
    <script>
    $(document).off('pageinit', '#accountpage').on('pageinit', '#accountpage', function() {
        $(document).off('click', '#btnlogout').on('click', '#btnlogout', function(){
            $.mobile.changePage("jqmlogin.html", {reloadPage: true});
        });
        console.log("pageinit in accountpage");
    });
    $(document).off('pageshow', '#accountpage').on('pageshow', '#accountpage', function() {
        console.log("pageshow in accountpage");
    });
    </script>
    <div data-role="content">
        <a id="btnlogout" href="#" data-role="button">Logout</a>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

在此设置中,如果用户刷新 account.html,该页面上的“注销”按钮仍然有效。