javascript 绑定 popstate 事件不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14748452/
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
binding popstate event not working
提问by mirelon
I have tried to type this code into the browser's console:
我试图将此代码输入浏览器的控制台:
window.onpopstate = function() {alert(1);}
and then click the back button. No alert has shown. Am I doing something wrong? Or is it not allowed to bind popstate event to a page from console?
然后单击后退按钮。没有显示警报。难道我做错了什么?还是不允许从控制台将 popstate 事件绑定到页面?
Using Chrome 24 and Firefox 18
使用 Chrome 24 和 Firefox 18
回答by Sean Hogan
Type this into the console
在控制台输入这个
window.onpopstate = function() {alert(1);}; history.pushState({}, '');
then click the back button.
然后单击后退按钮。
回答by Trev14
I prefer adding the popstate listener as follows, to prevent overwriting of what's already in window.onpopstate
:
我更喜欢按如下方式添加 popstate 侦听器,以防止覆盖已经存在的内容window.onpopstate
:
window.addEventListener('popstate', function(){alert(1);});