【问题标题】:What is the best way to handle browser back button for dynamic content?处理动态内容的浏览器后退按钮的最佳方法是什么?
【发布时间】:2018-01-25 20:51:09
【问题描述】:

我们目前有一个应用程序(sails/node js),其中向用户显示一组动态生成的项目。用户可以选择生成更多动态项目(使用按钮)或预览一个项目(新页面)。目前,更多项目按钮被实现为实现发布请求的 jquery 插件。

问题是,当用户单击更多项目按钮并选择一项进行预览,然后按浏览器返回按钮时,动态内容会丢失。

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

还有其他方法吗?任何帮助表示赞赏。我们对这种开发环境完全陌生。

【问题讨论】:

标签: javascript jquery sails.js


【解决方案1】:

您可以利用History API

var stateObj = { lastItemId: 456 }; // or { page: 3 }
history.pushState(stateObj, "page 2", "bar.html");

【讨论】:

    【解决方案2】:

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

    所以我这样定义preventBackButton ()

    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()

    $(document).ready(function() {
    
        preventBackButton();
        // Do other stuff...
    
    });
    

    【讨论】:

      猜你喜欢
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      • 2023-02-23
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      相关资源
      最近更新 更多