0

我编写了一个 jquery 导航脚本,它使用.load. 我还在使用带有 pushstate 和 popstate 的 HTML5 History API。

$(document).ready(function(){

$('.menu_top').on('click', function(e) {
    $("#loading").show();
    var href = $(this).attr('href');
    history.pushState({url: href}, '', href);
    $('#contentwrapper').fadeOut('normal').hide().load(href + " #contentwrapper > *");
    $('#contentwrapper').waitForImages(function() {
    $(this).fadeIn('slow');  
});

    $(document).ajaxSuccess(function() {
  $("#loading").delay(1000).fadeOut();
});

});
    var popped = ('state' in window.history), initialURL = location.href;
    $(window).bind('popstate', function(event){
    var initialPop = !popped && location.href == initialURL;
    popped = true;
    if ( initialPop ) return;
    var state = event.originalEvent.state;

    $('#contentwrapper').load(state.url + " #contentwrapper > *");
});

});

该代码大部分工作,浏览器的后退和前进按钮功能正常,直到您尝试在浏览器上点击“后退”以转到访问的原始页面。例如:

从第 1 页开始

点击链接到第 2 页 - 作品

点击链接到第 3 页 - 作品

点击“返回”第 2 页 - 有效

点击“返回”第 1 页 - 不起作用

...

控制台给出以下消息:

Uncaught TypeError: Cannot read property 'url' of null

这是我第一次使用popstate. 如何让浏览器导航回原始页面?我希望我能很好地解释这个问题。任何帮助,将不胜感激!

这是该问题的现场演示,如果您希望看到它的实际效果。

4

1 回答 1

0

我遇到了与上面和下面对我有用的更改相同的问题:

    <script type="text/javascript">

    var initialURL;
    var popped = (window.history.state != null), initialURL = location.href;

    window.onpopstate = function(event) {
    var counter =0;
     var everPushedSomething = false;

     var initialLoad= document.getElementById('hdninitload').value;

     var onloadPop = !everPushedSomething && location.href == initialURL ;

    if(onloadPop){counter = 1;}
    if(initialLoad == 'true'){counter = counter + 1;}


      everPushedSomething = true;
     if (counter != 2) { window.open(location.href, '_self'); }

     }  


    })(window);


    </script>


    <input id="hdninitload" type="hidden" value="true" />

    and Whenever I call history.PushState method,  set this hdninitialload control value to false. something like below:

    history.PushState('','title of the Page','/newPage.aspx'); document.getElementById('hdninitload').value = 'false';

    Hope this works for you as well.
于 2014-08-06T06:28:23.510 回答