为AJAX加载的内容操纵浏览器历史记录

时间:2017-09-20 15:43:47

标签: javascript jquery html browser-history

我的页面左侧是导航链接,右侧是内容div。导航链接HTML就像这样设置。

<a href="javascript:;" class="nav-link" data-mode="myModeValue">Test</a>

我已经设置了一个JavaScript函数,如下所示,我认为它将绑定到链接,将新状态推送到浏览器历史记录中,并根据数据模式值加载该链接的内容。前进是完美的,但是当我后退时,我必须再次点击两次才能回到之前的哈希,我不知道为什么。

这是我到目前为止所拥有的。

<script language="javascript">
    // Create var indicating the CURRENT mode we're on - home being the default when page loads
    currentMode = "home"; 
    // Push the default page (mode) into the history
    history.pushState(null, document.title, location.pathname + "#!/detail-mode/" + currentMode);

    // bind to my nav links
    $(document).on('click', '.nav-link', function(e){
        e.preventDefault();
        ajaxLoadVehicleSearchDetailContent($(this).data('mode'));
    });

    function ajaxLoadVehicleSearchDetailContent(mode) {
        // Get the mode and link object
        var thisMode = mode.toString().toLowerCase();
        var thisLink = $('a[data-mode="' + mode + '"]');
        // If we're switching to a different tab - continue
        if (currentMode != thisMode) {
            currentMode = thisMode;     
            // Get the content via AJAX
            $.ajax({
                url: "/myAjaxFunctionFileURL",
                type: "POST",
                data: { method:"getTabContent", mode:thisMode },
                success: function(result) {
                    history.pushState(null, document.title, location.pathname + "#!/detail-mode/" + thisMode);
                    // Update the content area - fadeOut,replace,fadeIn
                    $('#contentArea').fadeOut(globalAnimationDuration, function() {
                        $('#contentArea').html(result).fadeIn(globalAnimationDuration);
                        $('.nav-link').removeClass('current');  
                        thisLink.addClass('current');                   
                    });
                }
            });     
        }
    }

    // Listen for the popstate and load correct content when user goes BACK in history
    window.addEventListener("popstate", function() {
        if (location.hash.indexOf("#!") != -1) {
            var thisMode = location.hash.split("/").slice(-1)[0];           
            ajaxLoadVehicleSearchDetailContent(thisMode);           
        }
    }, false);
</script>

globalAnimationDuration var只是一个值为500的变量。

任何人都可以回想起为什么回去时的奇怪行为?或者甚至是一个很好的例子,展示了如何执行我可以遵循的任务并相应地更新我的方法?

JSFiddle Here

谢谢!

1 个答案:

答案 0 :(得分:0)

我明白了。由于我在前进和后退导航中都调用了相同的ajaxLoadVehicleSearchDetailContent,因此在单击返回时错误地向堆栈添加了项目。所以它会弹出堆栈中的项目,调用该函数然后将其重新添加到堆栈中,除非它是当前的选项卡。

我的解决方案为我的ajaxLoadVehicleSearchDetailContent()方法添加了另一个参数,如下所示。

function ajaxLoadVehicleSearchDetailContent(mode,backward) {
        // Get the mode and link object
        var thisMode = mode.toString().toLowerCase();
        var thisLink = $('a[data-mode="' + mode + '"]');
        // If we're switching to a different tab - continue
        if (currentMode != thisMode) {
            currentMode = thisMode;     
            // Get the content via AJAX
            $.ajax({
                url: "/myAjaxFunctionFileURL",
                type: "POST",
                data: { method:"getTabContent", mode:thisMode },
                success: function(result) {
                    if (!backward) history.pushState(null, document.title, location.pathname + "#!/detail-mode/" + thisMode);
                    // Update the content area - fadeOut,replace,fadeIn
                    $('#contentArea').fadeOut(globalAnimationDuration, function() {
                        $('#contentArea').html(result).fadeIn(globalAnimationDuration);
                        $('.nav-link').removeClass('current');  
                        thisLink.addClass('current');                   
                    });
                }
            });     
        }
    }

然后当我从导航链接中调用它时 - 发送false,当我从我的popstate事件中调用它时,我称之为true。

相关问题