首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >处理动态内容的浏览器后退按钮的最佳方式是什么?

处理动态内容的浏览器后退按钮的最佳方式是什么?
EN

Stack Overflow用户
提问于 2018-01-26 04:51:09
回答 2查看 978关注 0票数 1

我们目前有一个应用程序(sails/node js),向用户显示一组动态生成的项目。用户可以选择生成更多动态项目(使用按钮),也可以预览一个项目(新页面)。目前,more items按钮是作为实现post请求的jquery附加组件实现的。

问题是,当用户单击more items按钮并选择一个项目进行预览,然后按下浏览器的back按钮时,动态内容就会丢失。

我们看到不同的选项: 1.实现分页和无限滚动,并使用历史js来管理后退按钮2.使用当前设置的历史,并结合jquery来管理后退按钮。

有没有其他的方法?感谢您的帮助。我们对这个开发环境是完全陌生的。

EN

回答 2

Stack Overflow用户

发布于 2018-01-26 04:59:43

您可以利用History API

代码语言:javascript
复制
var stateObj = { lastItemId: 456 }; // or { page: 3 }
history.pushState(stateObj, "page 2", "bar.html");
票数 0
EN

Stack Overflow用户

发布于 2018-01-26 05:50:13

我发现的最简单的方法是“禁用”后退按钮点击。好吧,从技术上讲,没有办法禁用它,但您可以给最终用户以后退按钮已被禁用的外观。我最初是基于this blog post开发代码的。这是一本很好的读物,因为他详细地解释了方法。从那时起,我改进了他的代码,如下所示。

所以我这样定义preventBackButton ()

代码语言:javascript
复制
function preventBackButton () {
    // Triggered when the back button is pressed, it will detect if the url hash changes from #rms to #no-back.  If it does, then
    // it harmlessly changes the url hash forward again by going from "#no-back" to "#rms".

    // On initial page load, pushes states "#no-back" and "#rms" onto the history, making it the most recent "page" to detect future "back" button presses.
    var history_api = typeof history.pushState !== 'undefined';

    if ( history_api ) {
        history.pushState(null, '', '#no-back');
        history.pushState(null, '', '#rms');
    } else {
        location.hash = '#no-back';
        location.hash = '#rms';
    }

    // This function creates an event handler on hash changes.  This is coded to detect back button clicks.
    window.onhashchange = function() {
        // location.hash becomes "#no-back" when the user clicks back button
        if ( location.hash === '#no-back' ) {
            if ( history_api ) {
                history.pushState(null, '', '#rms');
            } else {
                location.hash = '#rms';
            }
        } 
    };

} // function preventBackButton ()

然后我在$(document).ready()中调用它

代码语言:javascript
复制
$(document).ready(function() {

    preventBackButton();
    // Do other stuff...

});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48451704

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档