我们知道JavaScript中非常早就提供了window.history对象,利用history对象的forward()、go()、back()方法可以方便实现不同页面之间的前进、后退等这样的导航功能。
可是AJAX操作。是不能用浏览器的前进和后退button进行导航的,由于浏览器并不会将AJAX操作增加到历史记录中。可是借助location.hash,我们可以自己实现AJAX操作的前进和后退。关于window.location.hash的具体介绍和使用方式,可以參考以下这2篇文章。
location.hash具体解释和 6 Things You Should Know About Fragment URLs。
我们须要知道下面2点:
1.假设location.hash发生了变化,那么浏览器地址栏url会发生变化。并且浏览器会产生1个历史记录。
2.假设location.hash发生了变化,会产生一个hashchange事件,我们能够处理这个事件。
<!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); recordHash(currentPageIndex); } // onhashchange能够监控hash变化 window.onhashchange=function(){ var hash = window.location.hash; var id = parseInt(hash.substr(1)); showPageAtIndex(id); }; function toNextPageWhenClick() { currentPageIndex++; if(isValidPageIndex(currentPageIndex)) { showPageAtIndex(currentPageIndex); recordHash(currentPageIndex); } else { return; } } function showPageAtIndex(id) { $("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)); } } function isValidPageIndex(id) { return id <= 5; } function isLastPage(id) { return id == 5; } function isHomePage(id) { return id == 0; } // hash改变,浏览器会自己主动生成一个历史记录 function recordHash(id) { window.location.hash=id; } </script> <style> .navigate{ height:100px; 300px; background-color:#0000ff; display:none; } .home{ height:100px; 300px; background-color:#00ff00; display:none; } .last{ height:100px; 300px; background-color:#ff0000; display:none; } </style> </head> <body> <input type="button" value="" onclick="toNextPageWhenClick();"> <div class="home" id="0">HOME PAGE</div> <div class="navigate" id="1">ajax1</div> <div class="navigate" id="2">ajax2</div> <div class="navigate" id="3">ajax3</div> <div class="navigate" id="4">ajax4</div> <div class="last" id="5">last page</div> </body> </html>