Javascript 如何添加浏览器历史记录状态?

Javascript 如何添加浏览器历史记录状态?,javascript,jquery,hashchange,browser-state,Javascript,Jquery,Hashchange,Browser State,因此,我看到很多人推荐使用隐藏--iFramehack,但我真正需要的是这项技术的另一半: function whenItemIsClicked() { window.location.hash = this.id; //some other stuff, like Ajax } //and then, if page is reloaded... $(document).ready(function(){ var loc = window.locati

因此,我看到很多人推荐使用隐藏--
iFrame
hack,但我真正需要的是这项技术的另一半:

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,这样上述技术就可以工作?

有一个事件称为“虽然不是每个人都支持它,但是…”。。。解决这个问题

该插件通过使用
window.onhashchange
(本机事件)跨浏览器工作(如果有)。如果不是,则每50毫秒轮询一次,并在散列更改时触发事件本身。使用,您的代码将如下所示:

$(window).hashchange(function() {
  var loc = window.location.hash;
  if(loc != '') $(loc).click();    
});
你只需要把代码放在一个地方。您可以在
document.ready
中触发它一次,只需在绑定事件后触发它,如上所述:

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