2015-02-06 58 views
0

當推到歷史和不改變URL設置數據:爲什麼與同一location.href(或空)按下時window.onpopstate空event.state

window.history.pushState({ 
    stateName: "myStateName", 
    randomData: window.Math.random() 
}, "myStateName", location.href); 

....然後聽

window.onpopstate = function(event) { 
    console.log(event.state); //logs null 
} 

您將大部分的時間得到null作爲狀態值,而不是:

{ 
    stateName: "myStateName", 
    randomData: 0.34234234234 
} 
流行事件,並通過在瀏覽器中按後退按鈕觸發它

我該如何解決這個問題,爲什麼會發生這種情況?

回答

1

這是一個奇怪的問題,據我所知,它沒有足夠的文件。我在尋找解決這個問題的方法時遇到了很多麻煩。經過一個小時的搜索引擎沮喪和嘗試/提出不同的解決方案,我注意到,當我將狀態推到兩次(或更多)狀態時,它開始工作。很明顯,event.state指的是被推送的倒數第二個狀態。

所以做這項工作的答案是推兩次,聽一次。

window.history.push(..); 
window.history.push(..); 

我希望這可以幫助別人!

相關問題