相关疑难解决方法(0)

如何在使用HTML5 pushState更改浏览器URL时处理后退按钮

我做了一个单页的网站.当用户单击菜单按钮时,内容将加载ajax.它工作正常.为了改善SEO并允许用户复制/过去不同内容的URL,我使用

function show_content() {
        // change URL in browser bar)
        window.history.pushState("", "Content", "/content.php");
        // ajax
        $content.load("ajax/content.php?id="+id);
}
Run Code Online (Sandbox Code Playgroud)

它工作正常.URL更改,浏览器不会重新加载页面

但是,当用户单击浏览器中的后退按钮时,URL将更改并且必须加载内容.

我做到了这一点,它的工作原理:

 window.onpopstate = function(event) {
        if (document.location.pathname == '/4-content.php') {
            show_content_1();
        }
        else if (document.location.pathname == '/1-content.php') {
            show_content_2();
        }
        else if (document.location.pathname == '/6-content.php') {
            show_content_();
        }
    };
Run Code Online (Sandbox Code Playgroud)

你知道是否有办法改进这段代码?

javascript ajax html5 browser-history pushstate

3
推荐指数
1
解决办法
8900
查看次数

标签 统计

ajax ×1

browser-history ×1

html5 ×1

javascript ×1

pushstate ×1