2012-03-20 7 views
2

私はjQueryを作成しました。を使用すると、ページを更新せずにコンテンツが読み込まれます。そのためのコードは次のとおりです。jQueryハッシュチェンジ方法

$(document).ready(function(){ 
// initial 
$('#content').load('content/index.php'); 

// handle menu clicks 
$('#navBar ul li ').click(function(){ 
var page = $(this).children('a').attr('href'); 
$('#content').load('content/'+ page +'.php'); 
return false; 
}); 
}); 

は今、私はその中に歴史の事のようなものを持ちたい、そのためのコードは次のとおりです。上が見つかり

(function(){ 
// Bind an event to window.onhashchange that, when the hash changes, gets the 
// hash and adds the class "selected" to any matching nav link. 
$(window).hashchange(function(){ 
var hash = location.hash; 
// Set the page title based on the hash. 
document.title = 'The hash is ' + (hash.replace(/^#/, '') || 'blank') + '.'; 
// Iterate over all nav links, setting the "selected" class as-appropriate. 
$('#nav a').each(function(){ 
var that = $(this); 
that[ that.attr('href') === hash ? 'addClass' : 'removeClass' ]('selected'); 
}); 
}) 
// Since the event is only triggered when the hash changes, we need to trigger 
// the event now, to handle the hash the page may have loaded with. 
$(window).hashchange(); 
}); 

http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/

私の質問をされます:どのように私は最初のコードで動作する2番目のコードを作ることができますか?あなたは

$('#content').load('content/index.php'); 
//create a cache object 
var cache = {}; 
// handle menu clicks 
$('#navBar ul li ').click(function(){ 
    var page = $(this).children('a').attr('href'); 
    //check if the page was already requested 
    if(cache[page] === undefined){ 
    //if not fetch the page from the server 
    $.get('content/'+ page +'.php', function(data){ 
     $('#content').html(data); 
     //save data in cache 
     cache[page] = data; 
    }else{ 
    //use data from cache 
    $('#content').html(cache[page]); 
    } 
    return false; 
}); 

答えて

0

。 HTML5 pushStateで動作し、HTML 4ハッシュタグにもフォールバックします。また、ページがリフレッシュされたときに状態モデルを保持するためにも機能します。

+0

これは、彼がコンテンツをロードしたくない、動作しませんので、私はそれをチェックアウトすることはできません。 – Youri

0

使用History JSような何かを行うことができますキャッシュを実装するために

+0

このリンクは質問に答えるかもしれませんが、答えの本質的な部分をここに含めて参考にしてください。リンクされたページが変更された場合、リンクのみの回答は無効になります。 –

+0

@MattThrowerと、まさにこのリンクには何が含まれていますか? – Qix

+0

@Qixレビューシステムからの自動メッセージです。いくつかのコードサンプルは、おそらく有用かもしれませんか? –

1

あなたはまだ答えを得ていないので、私はそれを書きます。コードを実行するには、プラグインjQuery hashchangeが必要です。

https://github.com/cowboy/jquery-hashchange

+1

このリンクは質問に答えるかもしれませんが、回答の重要な部分をここに含めて参照用のリンクを提供する方が良いでしょう。リンクされたページが変更された場合、リンクのみの回答は無効になります。 –

+0

このリンクは、必要なjavascriptファイルをダウンロードする場所を示すためのものです。 –

+0

まだ、彼らが使うことができるツールを指しているだけでは、何かをする方法を彼に伝えることにはなりません。 –

関連する問題