ページの履歴を保存するには、最も一般的でフル機能/サポートされている方法は、ハッシュ変更を使用することです。これは、あなたが移動すると、その変更を追跡できることyoursite/page.html#page1
を意味しyoursite/page.html#page2
、ハッシュを使用しているため、ブックマークと前後のボタンで取得できます。
jQuery History プロジェクトhttp://www.balupton.com/projects/jquery-historyを使用して、ハッシュの変更にバインドする優れた方法を見つけることができます
。
フル機能の AJAX 拡張もあり、Ajax リクエストを状態/ハッシュに簡単に統合して、Web サイトをフル機能の Web 2.0 アプリケーションに変換できます:
http://www.balupton.com/projects/jquery-ajaxy
どちらも、何が起こっているのか、何が起こっているのかを説明するために、デモ ページで優れたドキュメントを提供しています。
jQuery History の使用例を次に示します (デモ サイトから取得)。
// Bind a handler for ALL hash/state changes
$.History.bind(function(state){
// Update the current element to indicate which state we are now on
$current.text('Our current state is: ['+state+']');
// Update the page"s title with our current state on the end
document.title = document_title + ' | ' + state;
});
// Bind a handler for state: apricots
$.History.bind('/apricots',function(state){
// Update Menu
updateMenu(state);
// Show apricots tab, hide the other tabs
$tabs.hide();
$apricots.stop(true,true).fadeIn(200);
});
jQuery Ajaxy の例 (デモ サイトから取得):
'page': {
selector: '.ajaxy-page',
matches: /^\/pages\/?/,
request: function(){
// Log what is happening
window.console.debug('$.Ajaxy.configure.Controllers.page.request', [this,arguments]);
// Adjust Menu
$menu.children('.active').removeClass('active');
// Hide Content
$content.stop(true,true).fadeOut(400);
// Return true
return true;
},
response: function(){
// Prepare
var Ajaxy = $.Ajaxy; var data = this.State.Response.data; var state = this.state;
// Log what is happening
window.console.debug('$.Ajaxy.configure.Controllers.page.response', [this,arguments], data, state);
// Adjust Menu
$menu.children(':has(a[href*="'+state+'"])').addClass('active').siblings('.active').removeClass('active');
// Show Content
var Action = this;
$content.html(data.content).fadeIn(400,function(){
Action.documentReady($content);
});
// Return true
return true;
そして、クエリ文字列のパラメータを取得したい場合は(そうyoursite/page.html#page1?a.b=1&a.c=2
)、次のように使用できます。
$.History.bind(function(state){
var params = state.queryStringToJSON(); // would give you back {a:{b:1,c:2}}
}
これらのデモ リンクをチェックして、実際の動作を確認し、すべてのインストールと使用方法の詳細を確認してください。
編集:コードを確認したら、jQuery History で使用するために必要な作業はこれだけです。
変化する:
$('.tabbed_content .tabs li a').live('click',
function (e){
e.preventDefault();
switchTab($(this));
});
に:
// Bind a handler for ALL hash/state changes
$.History.bind(function(state){
switchTab(state);
});
または、他の領域にも jQuery History を使用する予定がある場合は、すべてのハッシュではなく、タブに対してのみ switchTab を呼び出すようにします。
// Bind a handler for ALL hash/state changes
$.History.bind(function(state){
if ( $('.tabbed_content > .content > li[id='+state+']').length ) switchTab(state);
});
onclick イベントを使用しなくなりました。代わりに、hashchange を検出する jQuery History にバインドします。これは理解すべき最も重要な概念です。たとえば、サイトをブックマークしてから戻ったとしても、クリックしたことはありません。代わりに、クリックを変更してハッシュ変更にバインドします。クリックしたり、ブックマークしたり、前後に移動したりすると、ハッシュ変更が常に発生します:-)