使用 Ajax 之後,如何照顧「前進/後退」鈕

30 views
Skip to first unread message

gugod

unread,
Nov 5, 2007, 6:56:38 AM11/5/07
to hsinchu.js
如果你剛開始寫東西的話,可以直接用 jQuery 的 plugin:

* http://www.mikage.to/jquery/jquery_history.html
* http://stilbuero.de/jquery/history/

這兩者的 Code 大同小異,做法也完全一樣。都是利用 URL 的 hash (井號後面的字串)來表示目前畫面的狀態。

在兩大瀏灠器間的做法差異大略摘要如下:

Firefox:

只要正確地設置 URL hash 便可,不用多做處理。只要 hash 的值不同, Firefox 便會在其瀏灠記錄留下一筆,因此「前進/後退」
鈕便可直接使用。而且不會整頁載入

IE:

改變 URL 的 hash,並不會讓 IE 在瀏灠記錄裡多加一筆,需要另外想辨法將其塞入瀏灠記錄中。目前已知的做法之一是透過 iframe。大
致上的方法如下 (with jQuery):

var iframe_obj = $("<iframe style='display:none;'></
iframe>").appendTo(document.body).get(0);
var iframe_doc = iframe_obj.contentWindow.document
iframe_doc.open();
iframe_doc.close();
iframe_doc.location.hash = "..."

連續對 iframe_doc 呼叫 open(), 後 close(),便會在瀏灠記錄裡記下一筆。但若要知道使用者是否已經按下「後退」鈕,便要
有個 interval call 去不斷地看:

var current_hash = location.hash;
setInterval(function() {
if ( iframe_doc.location.hash != current_hash )
location.hash = iframe_doc.location.hash
}, 200);

只要 iframe_doc.location.hash 的值一改,便表示使用者按下了前進、後退鈕。再馬上把主視窗的
location.hash 改成 iframe_doc.location.hash。而這之後其實還需要有其他的程式去依照
location.hash 的值,將正確的頁面重新載入。

Safari 與 Opera 的做法又不一樣,要比麻煩各有千秋、不相上下。日後看懂之後,再來分享。

Reply all
Reply to author
Forward
0 new messages