Jquery Mobile - 检测页面刷新 - 返回首页

5

在Jquery Mobile HTML5页面中,是否可能检测到页面刷新?

作为客户项目的一部分,我正在构建一个测验 - 测验通过jquery mobile div页面在一个html页面内导航.. 所以例如,如果用户在index.html#quizpage3上并刷新,则希望检测到刷新并将导航返回到index.html。

这是可能的吗?

谢谢 保罗

6个回答

3
这是我正在使用的解决方案。在编写时,它似乎能够正常工作,因此可能会对某些人有所帮助。但是,只是一个快速修复程序,为了更好的功能,最好在服务器端处理。
首先注意,此代码放置在JQM代码之前。(来自JQM网站:因为mobileinit事件会立即触发,所以您需要在加载jQuery Mobile之前绑定事件处理程序)。我们获取当前页面的哈希值,但我们不想在某些页面(如主页)上刷新。
<script type="text/javascript">
        var needRedirect = false;
        $(document).bind("mobileinit", function(){
            var thisPage = location.hash;
            if (thisPage != '' && thisPage != '#homepage' && thisPage != '#page1') {
                needRedirect = true;
            }
        });
    </script>
    <script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>

然后在你自己的代码开头:

if (needRedirect) {
    $.mobile.changePage("#homepage");
    needRedirect = false;
}

1
我的答案与Patch的类似,但我所做的只是在$(document).ready行之前添加以下内容到本地引用的js文件的顶部。您也可以将其添加到标题中的任何HTML脚本标记中。
if (location.hash != "" && location.hash != "pageHome") {
    var url = location.href;
    url = url.replace(location.hash,"");
    location.replace(url);
}

1

好的,这是一个开始,每次您导航到另一个页面时,您应该得到刷新控制台日志:

JS

$("div:jqmData(role='page')").live('pagehide',function(){
    console.log('page refreshed, redirect to home');
    $.mobile.changePage( "#home", { transition: "slideup"} );
});​

HTML

<div data-role="page" id="home">
    <div data-role="content">
        Hello Refresh
        <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="f">
            <li data-role="list-divider">Home</li>
            <li><a href="#page2">Page 2</a></li>
        </ul>
    </div>
</div>

<div data-role="page" id="page2" data-theme="a">
    <div data-role="content">
        Hello Page 2
        <ul data-role="listview" data-inset="true" data-theme="a" data-dividertheme="a">
            <li data-role="list-divider">Page 2</li>
            <li><a href="#home">Home</a></li>
        </ul>
    </div>
</div>​

也许其他事件会更适合:


0

我认为这更简单

$(document).on("pagebeforeshow", function() {
    window.location = "page";
});

0
您可以在$(function() {});方法中获取URL(仅在页面加载时运行),如果它包含#,则重定向到主页。 编辑:或者使用window.onload = function ...作为纯JS的替代方案。

0

我有点晚了,但我采用了Patch的想法来创建一个非常简单的解决方案。 将其放入script标签或在$(document).ready()之前的JS文件中。

checkPage();

function checkPage() {
    var _hash = location.hash;

    if (_hash != '' && _hash != "#home") {
        var _url = location.href.replace(_hash, "");
        window.location.href = _url;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接