2011-09-24 91 views
2

我已经设置了一个页面,当您单击某个链接时,内容会更改,而不会刷新页面,并且URL也会使用完全相同的命令(这就是它的代码)命令:如何更改网址并检测后退按钮

window.history.pushState("object or string", "title", "/photo.php"); 

但是,当用户点击后退按钮时,内容不会改回。我该怎么做? 我有这样的想法,因为当你在脸书上点击主页上的图片,当你点击后退按钮(两次,我认为这是一个错误),你回到家里,网址变回,页面不'根本不需要刷新。

+0

这个问题应该提供一个答案:http://stackoverflow.com/questions/6359327/detect-back-button-click-in-browser – thomasfedb

+0

歌剧没有按发送onbeforeunload事件 – Dimitar

+0

查看Ben Alman的JQuery BBQ。 BBQ代表后退按钮和查询库。 http://benalman.com/projects/jquery-bbq-plugin/ –

回答

3

您可以像这样使用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" 
    } 
}; 
+0

你能给我一个更好的例子,因为我不明白它 – Dimitar

+0

@Dimitar:希望我改进了我的答案。 – pimvdb

+0

非常感谢 – Dimitar

1

这个答案已经给出,但我会试着解释我了解使用什么pushState的 考虑您的网址是“google.com/gmail”

词根记忆CURRENTURL为临时URL,所以您的浏览器将显示此URL。在这一步中,堆栈中会有一个URL,即google.com/gmail#!/tempURL

history.replaceState(null, document.title, location.pathname+"#!/tempURL"); 

2.Push的previousURL作为新的国家所以现在你的浏览器将显示previousURL即google.com/gmail

history.pushState(null, document.title, location.pathname); 

堆栈的当前状态


第一个元素: google.com/gmail


最后元件: google.com/gmail#!/tempURL


3.Now添加监听器来监听事件

window.addEventListener("popstate", function() { 
     if(location.hash === "#!/tempURL") { 
     history.replaceState(null, document.title, location.pathname); 
     //replaces first element of last element of stack with google.com/gmail so can be used further 
     setTimeout(function(){ 
      location.replace("http://www.yahoo.com/"); 
     },0); 
     } 
    }, false);