javascript popstate 事件处理程序似乎不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14112341/
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
popstate event handler seems not to work
提问by petwho
I'm having a problem with a 'popstate' event handler, this is my code:
我的“popstate”事件处理程序有问题,这是我的代码:
window.addEventListener("popstate", function (event){
if (event.state) {
alert('abc')
}
});
// The data object is arbitrary and is passed with the popstate event.
var dataObject = {
createdAt: '2011-10-10',
author: 'donnamoss'
};
var url = '/posts/new-url';
history.pushState(dataObject, document.title, url);
I expected this code will pop up an alert box when it's executed but, nothing happens.
我希望这段代码在执行时会弹出一个警告框,但没有任何反应。
Is there anything wrong here?
这里有什么问题吗?
Thank you.
谢谢你。
回答by otakustay
pushState
do not trigger the popstate
event, only clicking back / forward button (or use backspace) or invoking history.back()
/ history.go(n)
would trigger this event.
pushState
不触发popstate
事件,只有单击后退/前进按钮(或使用退格键)或调用history.back()
/history.go(n)
才会触发此事件。
Also, in webkit browsers, a popstate
event would be triggered after page's onload
event, but Firefox and IE do not have this behavior.
另外,在 webkit 浏览器中,popstate
会在页面onload
事件之后触发一个事件,但 Firefox 和 IE 没有这种行为。
回答by Arun P Johny
No it will not,
不,不会,
As per MDN documentation
根据MDN 文档
Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript).
请注意,仅调用 history.pushState() 或 history.replaceState() 不会触发 popstate 事件。popstate 事件仅通过执行浏览器操作触发,例如单击后退按钮(或在 JavaScript 中调用 history.back())。
Again as per this questionthe popstate
event is not triggered in Chrome
when you call pushState()
.
同样按照这一问题的popstate
事件不会在触发Chrome
时调用pushState()
。
回答by u283863
history.pushState()
will not trigger the popstate
event by definition.
history.pushState()
popstate
根据定义不会触发事件。
The popstate event is fired in certain cases when navigating to a session history entry.
在导航到会话历史记录条目时,在某些情况下会触发 popstate 事件。
This event is intended to be only triggered when navigating to a history entry, either by pressing the back/forward button, or history.go/back
.
此事件仅在导航到历史条目时触发,通过按后退/前进按钮或history.go/back
。