我使用History.js(jquery.history.js v1.8b2)。 Chrome版本30.0.1599.101米。當我從外部鏈接導航回來時,是否應該觸發window.statechange?
我無法弄清楚如何讓History.js以我期望的方式工作。
我有一個頁面,有兩個鏈接。第一個模擬ajax操作。它只是將頁面中的<h2>
中的文本從「開始」更改爲「2」。第二個鏈接僅指向google.com。
這是我做的:
- 清除高速緩存中的鉻
- 加載頁面
- 點擊第一個鏈接(我稱之爲pushState的,statechange發生有更新我的文字爲「2」)
- 單擊google.com鏈接(轉到谷歌)
- 單擊瀏覽器後退按鈕。
當後退按鈕單擊時,我期望應該調用statechange處理程序,然後我會得到我的狀態對象,以便我可以將文本恢復爲「2」。
但處理程序沒有被調用。所以我的頁面留下了文本「開始」(緩存頁面在瀏覽器中)。有趣的是,url被設置爲我在pushState調用中推送的「2」版本。
我錯過了什麼嗎?這是我的代碼:
<h2 id="state">start</h2>
<a id="2" class="button" href="#">Goto State 2</a>
<a href="http://google.com">Goto google</a>
<script type="text/javascript">
$(function() {
History.Adapter.bind(window, "statechange", function() {
console.log("statechange called");
var state = History.getState();
if (state.data.mystate) {
// Restore the old state
$("#state").text(state.data.mystate);
} else {
// Start state
$("#state").text("start");
}
});
$(".button").click(function(e) {
// push the state we're transitioning to
var newState = $(this).attr("id");
History.pushState(
{ mystate: newState },
"at state " + newState,
"http://localhost:50494/PushState?state=" + newState);
// statechange will be called now, and we'll update the page from our newState
e.preventDefault();
});
});
</script>