2010-09-03 138 views
1

所以我看到很多人推荐的hidden- iFrame黑客是jQuery history plugin但我真正需要的是这种技术的另一半:如何添加浏览器历史记录状态?

function whenItemIsClicked() 
    { 
    window.location.hash = this.id; 
    //some other stuff, like Ajax 
    } 

//and then, if page is reloaded... 
$(document).ready(function(){ 
    var loc = window.location.hash; 
    //if there happens to be a hash, navigate to corresponding content 
    if(loc != '') $(loc).click(); 
}); 

这两项工作的伟大。现在,我想附加这两行

var loc = window.location.hash; 
    if(loc != '') $(loc).click(); 

给一个事件,但似乎没有一个将会一直被后退按钮触发。有没有办法添加一个浏览器历史状态,将保存当前的URL,以便上述技术将工作?

回答

2

有一个事件叫做window.onhashchange,虽然不是所有人都支持它,但是...... there's a plugin by Ben Alman解决了这个问题。

该插件通过使用window.onhashchange(本机事件)使其跨浏览器工作,如果它在那里的话。如果不是,则每50ms轮询一次,如果散列值发生变化,则触发事件本身。使用the plugin,你的代码应该是这样的:

$(window).hashchange(function() { 
    var loc = window.location.hash; 
    if(loc != '') $(loc).click();  
}); 

你只需要在一个地方的代码。你可以在document.ready之后通过触发事件触发一次,如上面这样绑定:

$(function(){ 
    $(window).hashchange(); 
});