如何更改网址和检测后退按钮

Dim*_*rov 4 html javascript

我已经建立了一个页面,当您单击链接时,内容会更改而不会刷新页面,因此,使用完全相同的命令(这就是代码中的命令)的URL也是如此:

window.history.pushState("object or string", "title", "/photo.php");
Run Code Online (Sandbox Code Playgroud)

但是,当用户单击“后退”按钮时,内容不会退回。我该怎么做?我考虑到这一点,因为在Facebook中单击主页上的图片,然后单击后退按钮(两次我认为这是一个错误)时,您回到主页,URL变回而页面却没有完全刷新。

pim*_*vdb 5

您可以这样使用onpopstate。当使用导航按钮时也会触发。

http://jsfiddle.net/54LfW/4/

window.onpopstate = function(e) { // executed when using the back button for example
    alert("Current location: " + location.href); // location.href is current location

    var data = e.state;
    if(data) {
        alert(JSON.stringify(e.state)); // additional data like your "object or string"
    }
};
Run Code Online (Sandbox Code Playgroud)