具有onpopstate的后退按钮控件

时间:2019-12-22 00:15:48

标签: javascript pushstate popstate

我正在使用pushstate api推送查询URL,因此可以将其附加到我的服务器代码中。现在我的js代码看起来像这样

<script type="text/javascript">

//Pagination part
    $('.main-section').on('click', '.pagination > li > a', function (event) {
    var page = $(this).text();
    event.preventDefault();
    if ($(this).attr('href') != '#' && $(this).attr('class') == 'com') {

        // Update the browser's address bar
        history.pushState(null, null, $(this).attr('href')); 

window.onpopstate = function(event) {

        window.location.replace(window.location.pathname);

}

        $("html, body").animate({scrollTop: 0}, "slow");
        $.request('onFilterProduct', {
            data: {page: page},

        });
    }
});

</script>

当我单击后退按钮时,它可以正常工作,并且仅加载我想要的location.pathname,但是当我再次单击后退按钮时,它显示了加载了pushstate的URL,这是我不想要的。我希望它加载location.pathname,在我的情况下是产品列表,当用户再次单击“后退”按钮时,它将显示子类别页面,然后显示主页,而不是返回历史记录。

0 个答案:

没有答案