如今有許多網站支持SPI(single page interface),和傳統的MPI(multi page interface)比起來,它無需載入新的網頁,速度會快不少,用戶體驗也會好不少。惟一的問題是若是你的頁面改動很大,好比切換tab,頁面大部份內容由ajax載入。用戶會覺得跳轉到另外一個頁面,這時若是他們點擊後退按鈕,SPI就會出問題了,由於咱們只有一個頁面。 javascript
解決辦法就是使用hashchange事件。一方面是當你切換tab時,在url里加入hash,javascript裏是location.hash;另外一方面是當hash變化是捕捉到該事件,大部分新的瀏覽器支持onhashchange事件。 html
至於IE6,7,咱們須要用iframe去模擬這兩個方面。 java
這裏推薦一個jquery plugin: http://benalman.com/projects/jquery-hashchange-plugin/ jquery
個人一個例子: ajax
//include jquery plugin var prefix = 'hash-'; // Bind the event. $(window).hashchange( function(){ var hash = window.location.hash.replace( /^[^#]*#?(.*)$/, '$1' ); if((hash == (prefix+'tab4')) || ((hash == ''))){ if($('#blockdisplay4:visible').length == 0){ } }else if((hash == (prefix+'tab1')) || ((hash == '') ) ){ if($('#blockdisplay1:visible').length == 0){ } } }) // Trigger the event (useful on page load). $(window).hashchange(); $('a[href]').live('click',function(){ var hash = window.location.hash.replace( /^[^#]*#?(.*)$/, '$1' ); var newhash = prefix + $(this).attr('href').replace( /^[^#]*#?(.*)$/, '$1' ); if(hash != newhash){ window.location.hash = newhash; } });最後注意hash的名字不能是html中已有的id,否則ie會出問題:
http://stackoverflow.com/questions/1078501/keeping-history-of-hash-anchor-changes-in-javascript 瀏覽器
Surprise quirk bonus #1! In Internet Explorer 6, whenever there's a question mark in the hash, this gets extracted and put in the location.searchproperty! It is removed from the location.hash property. If there is a real query string, however, location.search will contain that one instead, and you'll only be able to get the whole true hash by parsing the location.href property. ide
Surprise quirk bonus #2! If the location.search property is set, any subsequent # characters will be removed from the location.href (and location.hash) property. In Internet Explorer 6 this means that whenever there's a question mark in the path or the hash, you'll experience this quirk. In Internet Explorer 7, this quirk only occurs when there's a question mark in the path. Don't you just love the consistency in Internet Explorer? 網站
Surprise quirk bonus #3! If another element on the page has the same id as the value of a hash, that hash will totally mess up the history. So rule of thumb is to avoid hashes with the same id as any elements on the page. If the hashes are generated dynamically and may collide with ids, consider using a prefix/suffix. ui