2011-09-24 89 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);