开发者

How do I add a browser history state?

So I see a lot of people recommend the hidden-iFrame hack that is jQuery history plugin but all I really need is the other half of this technique:

function whenItemIsClicked()
    {
    window.l开发者_StackOverflow中文版ocation.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();
});

Both of these work great. Now, I'd like to attach these two lines

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

to an event, but it seems there isn't one that will be triggered consistently by the back button. Is there a way to add a browser history state that will save the present URL so the above technique will work?


There's an event called window.onhashchange though not everyone supports it yet, but...there's a plugin by Ben Alman to solve that issue.

The plugin makes it work cross-browser by using window.onhashchange (the native event) if it's there. If not, it polls every 50ms and triggers the event itself, if the hash changes. Using the plugin, your code would look like this:

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

You just need that code in one place. You can trigger it once in document.ready by just firing the event after it's bound like above doing this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜