jQuery hashchange怎么办?

时间:2012-03-20 12:03:18

标签: ajax jquery

我做了一个jQuery的事情; with将加载内容而不刷新页面。代码是:

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

我的问题是:如何让第二个代码与第一个代码一起使用?

3 个答案:

答案 0 :(得分:1)

由于你还没有得到答案,我会写出来。您需要插件jQuery hashchange才能运行代码。

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

答案 1 :(得分: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;
});

答案 2 :(得分:0)

使用History JS。它适用于HTML5 pushState,也可以回退到HTML 4主题标签。也适用于在刷新页面时保持状态模型。