【问题标题】:Usage of onpopstate with Balupton's History.js to go back使用 onpopstate 和 Balupton 的 History.js 返回
【发布时间】:2012-01-05 09:05:15
【问题描述】:

我的目标是存储网站的当前状态,以便我可以通过按浏览器的后退按钮返回到该状态。目前,我使用 HTML5 原生函数使用 pushState 和 popState 实现了这一点,如下所示:

<script type="text/javascript">
  $("a").click(function(e) {
    $("#element").load($(this).attr('href') + ' #otherElement');
    $("html, body").animate({ scrollTop: 0 }, 0);
    previous_page = location.href;
    window.history.pushState({page: $(this).index()}, $(this).html(), $(this).attr('href'));
    e.preventDefault();
    return false;
  });

  window.popupstate = function(e) {
    location.reload();
  }
</script>

这段代码在 Firefox 4 中按预期工作。但是,在 Chrome 中,页面会永久重新加载。因此,我想使用 Balupton 的 History.js 库在所有浏览器中运行代码 sn-p,但我发现 Balupton 页面上的示例不是很有帮助。

我尝试了以下方法(不起作用):

var History = window.History;
History.pushState({state:'root'},'root',$(this).attr('href'));

$("a").click(function(e) {
  $("#element").load($(this).attr('href') + ' #otherElement');
  $("html, body").animate({ scrollTop: 0 }, 0);
  History.pushState({state:$(this).attr('href')},$(this).attr('href'),$(this).attr('href'));
  return false;
});

History.Adapter.bind(window,'statechange',function(){ 
    var State = History.getState(); // Note: We are using History.getState() instead of event.state
    History.log('statechange:', State.data, State.title, State.url);
    if (State.title == 'root') {
        History.back();
        location.reload();
    }
});

谢谢。

【问题讨论】:

    标签: javascript jquery html history.js


    【解决方案1】:

    我为我的问题找到了可行的解决方案。由于我在替换整个 DOM 路径时丢失了绑定,因此我只需要按如下方式隐藏/显示元素:

    var History = window.History;
    
    $("a").live('click', function(e) {
        if ($(this).attr('href').startsWith('corpus-')) {
            $("#element").hide();
            $("#newElement").load($(this).attr('href') + ' #otherElement');
            $("html, body").animate({ scrollTop: 0 }, 0);
            History.pushState({state:$(this).attr('href')},$(this).attr('href'),$(this).attr('href'));
            return false;
        }
    });
    
    History.Adapter.bind(window,'statechange',function(){ 
        var State = History.getState();
        History.log('statechange:', State.data, State.title, State.url);
        $("#element").toggle();
        $("#newElement").toggle();
    });
    

    解决方案还不是很理想。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      相关资源
      最近更新 更多