HTML5新特性展示利用history.replaceState()修改記錄,html5replacestate
在上一篇文章中介紹history.pushState()的時候,我們提到location.hash存在的3個問題。第一個問題:url會發生改變,這個很容易理解。現在我們看下第二個問題和第三個問題,即如何修改瀏覽器的記錄,如何讓記錄儲存更多狀態相關的資訊。狀態相關的資訊上一篇部落格其實已經很容易看出來了,history.pushState()的第一個參數是javascript對象,我們當然可以在這個對象中存放任何我們想要的資料。本文我們主要看一下,如何利用histroy.replaceState修改瀏覽數的記錄。
還是上一篇文章中的例子,假如我們要實現這樣的功能:在當前頁面顯示這個頁面被訪問的次數。很顯然通過瀏覽器的前進和後退按鈕,我們可以無限多次地訪問某個頁面。但是我們並不希望產生更多的記錄,因為我在A頁面和B頁面之前跳過來跳過去,說白了就是2個記錄,只不過頁面資訊有變化而已。通過pushState和location.hash是無法達到這個要求的,因為這2種方式都是產生新的記錄,無法修改已有的記錄。這個時候replaceState就排上用場了。
<!DOCTYPE html> <html><head><meta charset="utf-8"><script type="text/javascript" src="jquery-1.11.1.min.js"></script><script type="text/javascript">var currentPageIndex = 0;window.onload = function(){currentPageIndex = 0;showPageAtIndex(currentPageIndex,1);addHistory(currentPageIndex);}// onpopstate可以監控state變化window.onpopstate = function(e){if(history.state){var state = history.state;var count = 1 + state.visitTime;showPageAtIndex(state.id,count);// 修改目前狀態資訊(修改記錄)history.replaceState({"id":state.id,"visitTime":count},"","");}}function toNextPageWhenClick(){currentPageIndex++;if(isValidPageIndex(currentPageIndex)){showPageAtIndex(currentPageIndex, 1);addHistory(currentPageIndex);}else{return;}}function showPageAtIndex(id,count){$("div[id!="+id+"]").hide();$("#"+id).show();if(isHomePage(id)){$("input").attr("value","current is home page,next page=1");}else if(isLastPage(id)){$("input").attr("value","current page="+id+", it is the end.");}else{$("input").attr("value","current page="+id+",next page="+(id+1));}$("#"+id).find("span").text(count);}function isValidPageIndex(id){return id <= 5;}function isLastPage(id){return id == 5;}function isHomePage(id){return id == 0;}// 增加記錄function addHistory(id){history.pushState({"id":id,"visitTime":1},"","");}</script><style>.navigate{height:100px;width:300px;background-color:#0000ff;display:none;}.home{height:100px;width:300px;background-color:#00ff00;display:none;}.last{height:100px;width:300px;background-color:#ff0000;display:none;}</style></head> <body><input type="button" value="" onclick="toNextPageWhenClick();"><div class="home" id="0">HOME PAGE.this is <span></span> time to visit this page.</div><div class="navigate" id="1">ajax1.this is <span></span> time to visit this page.</div><div class="navigate" id="2">ajax2.this is <span></span> time to visit this page.</div><div class="navigate" id="3">ajax3.this is <span></span> time to visit this page.</div><div class="navigate" id="4">ajax4.this is <span></span> time to visit this page.</div><div class="last" id="5">last page.this is <span></span> time to visit this page.</div></body></html>
在onpopstate事件處理函數中,我們拿到了當前記錄的狀態資訊,之後再用replaceState修改狀態資訊。就這樣,我們修改了狀態資訊(修改了記錄),但是並沒有產生新的記錄。這是用pushState和location.hash無法實現的。