2012-03-20 112 views
2

我做了一個jQuery的東西;將會在不刷新頁面的情況下加載內容。該代碼是:jQuery hashchange該怎麼辦?

$(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/

我的問題是:我如何使第二個代碼與第一個代碼一起工作?

回答

0

要實現緩存,你可以做類似

$('#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

這樣可不行,他不希望加載的內容,所以我不能檢查出來。 – Youri 2012-03-20 12:43:52

0

使用History JS。它適用於HTML5 pushState,也可以回退到HTML 4主題標籤。還可以在頁面刷新時保持狀態模型。

+0

儘管這個鏈接可能回答這個問題,但最好在這裏包含答案的基本部分,並提供供參考的鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 – 2014-07-25 15:49:47

+0

@MattThrower,他究竟會在這個鏈接中包含什麼? – Qix 2014-07-25 15:58:11

+0

@Qix這是來自審查系統的自動消息。一些代碼示例可能有用嗎? – 2014-07-25 15:59:45

1

既然你還沒有得到答案,我會寫它。您需要運行代碼的插件jQuery hashchange

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

+1

雖然這個鏈接可能回答這個問題,但最好在這裏包含答案的重要部分,並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 – 2014-07-25 16:04:06

+0

該鏈接僅用於向他顯示下載所需JavaScript文件的位置。 – 2014-07-25 18:39:14

+0

不過,只要指出一個他們可以使用的工具並不算是告訴他如何做某件事。 – 2014-07-25 19:19:33