How can I detect the back/forwards buttons being clicked when using History.js?

∥☆過路亽.° 提交于 2019-12-18 05:55:12

问题


Im using History.js (click) with jQuery in my code.

When loading new content via ajax i use:

History.pushState({my:stateobject},"newtitle","supernewurl");

This seems to work since the URL is updated in the browser.

However, I don't get it where I can hook up my code whenever a back or forward button is pressed. Which method/event is used for this?


回答1:


You need to bind an event handler to the statechange event, like this:

$(window).bind('statechange',function(){
// Do something, inspect History.getState() to decide what
})

There is a complete javascript snippet that comes with History.js, which can be used to 'ajaxify' a site completely: https://github.com/browserstate/ajaxify

Take a look there for more inspiration.




回答2:


You wouldn't capture the back click event, as there is none.

What you want to do is make sure the history object is in the right state by using window.history.pushState, window.history.popState, window.history.replaceState methods.

https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history




回答3:


I was able to use the "onPopState" event to trigger my custom AJAX code.

window.onpopstate = function(event) {
  $(fellowModal).foundation('reveal', 'close');
};

I tried several other things and that is what worked for me.



来源:https://stackoverflow.com/questions/11379411/how-can-i-detect-the-back-forwards-buttons-being-clicked-when-using-history-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!