jQuery 使用 History.js 时如何检测被单击的后退/前进按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11379411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I detect the back/forwards buttons being clicked when using History.js?
提问by Joey
Im using History.js (click) with jQuery in my code.
我在我的代码中使用 History.js(单击)和 jQuery。
When loading new content via ajax i use:
通过ajax加载新内容时,我使用:
History.pushState({my:stateobject},"newtitle","supernewurl");
This seems to work since the URL is updated in the browser.
这似乎有效,因为 URL 在浏览器中更新。
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?
但是,每当按下后退或前进按钮时,我都无法连接代码。为此使用哪种方法/事件?
回答by jgivoni
You need to bind an event handler to the statechange
event, like this:
您需要将事件处理程序绑定到statechange
事件,如下所示:
$(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
History.js 附带了一个完整的 javascript 片段,可用于完全“ajaxify”站点:https: //github.com/browserstate/ajaxify
Take a look there for more inspiration.
看看那里以获得更多灵感。
回答by xandercoded
You wouldn't capture the back click event, as there is none.
您不会捕获back click event,因为没有。
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.
您要做的是history
使用window.history.pushState
, window.history.popState
,window.history.replaceState
方法确保对象处于正确的状态。
https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history
https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history
回答by Chris Roane
I was able to use the "onPopState" event to trigger my custom AJAX code.
我能够使用“onPopState”事件来触发我的自定义 AJAX 代码。
window.onpopstate = function(event) {
$(fellowModal).foundation('reveal', 'close');
};
I tried several other things and that is what worked for me.
我尝试了其他几件事,这对我有用。