【问题标题】:popstate event on history api does not fire历史 API 上的 popstate 事件不会触发
【发布时间】: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/ 的一部分
  • 由于您的代码不清楚如何加载脚本,请尝试将其添加到 &lt;/body&gt; 结束标记之前。

标签: javascript html html5-history


【解决方案1】:

基于此处的定义:https://developer.mozilla.org/en-US/docs/Web/Events/popstate

当活动的历史条目改变时会触发 popstate 事件。如果 被激活的历史条目是通过调用创建的 history.pushState() 或受到调用的影响 history.replaceState(),popstate 事件的 state 属性包含一个 历史条目的状态对象的副本。

请注意,只需调用 history.pushState() 或 history.replaceState() 不会触发 popstate 事件。仅触发 popstate 事件 通过执行浏览器操作,例如单击后退按钮(或 在 JavaScript 中调用 history.back()。

浏览器倾向于在页面加载时以不同方式处理 popstate 事件。 Chrome 和 Safari 总是在页面加载时发出 popstate 事件,但是 Firefox 没有。

如果你每次点击链接时看到http://html5doctor.com/demos/history/的源代码,它会调用updateContent函数(也是popstate的事件处理函数)然后它调用pushState。

【讨论】:

    猜你喜欢
    • 2012-06-12
    • 1970-01-01
    • 2012-01-11
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    相关资源
    最近更新 更多