2012-03-20 111 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