【发布时间】:2014-05-18 13:37:16
【问题描述】:
我有一个简单的代码来测试html5的history api
只是一些按钮
<button name="hey1" onClick="historytestone();">history test one</button>
<button name="hey2" onClick="historytesttwo();">history test two</button>
<button name="hey3" onClick="historytestthree();">history test three</button>
<button name="hey4" onClick="historytestfour();">history test four</button>
<button name="hey5" onClick="historytestfive();">history test five</button>
而我的js就像
function historytestone(){
history.pushState({page: "ross"}, "ross","ross.html");
}
function historytesttwo(){
history.pushState({page: "monica"}, "monica","monica.html");
}
function historytestthree(){
history.pushState({page: "chandler"}, "chandler","chandler.html");
}
function historytestfour(){
history.pushState({page: "joy"}, "joy","joy.html");
}
function historytestfive(){
history.pushState({page: "rachel"}, "rachel","rachel.html?a=1&b=2");
}
// this does not work
window.addEventListener("popstate", function(event) {
alert("hello");
});
//nor this works
window.onpopstate=function(event){
alert("hello");
}
当我尝试侦听 popstate 事件时,控制台上没有任何警报和错误。不管我使用什么语法,我什么都得不到。
抱歉,我看不出有什么问题。请解释一下。
编辑
这是我的问题。 这是我的代码here,这是我基于here 的演示。
现在,我相信我的代码是演示的简化版本。
我必须单击浏览器的“返回”按钮才能触发popstate 事件(请参阅警报)。但该演示只需单击名称即可触发popstate 事件(更改内容)。
为什么会这样?为什么我必须点击后退按钮而演示没有,即使是相同的代码?再次感谢
【问题讨论】:
-
你在哪个浏览器上测试这个?
-
@TimVermaelen Vermaelen Google Chrome v. 34.0.1847.131
-
这可能是您的加载问题。它对我来说很好用:demo
-
@TimVermaelen 你的意思是像
window.onload='pushState()'?但是,历史 API 的重点不是加载页面。我的代码基于此演示http://html5doctor.com/demos/history/,它是此http://html5doctor.com/history-api/的一部分 -
由于您的代码不清楚如何加载脚本,请尝试将其添加到
</body>结束标记之前。
标签: javascript html html5-history