Popstate - 将弹出状态传递给事件处理程序

Lyn*_*ley 9 javascript browser-history

以下代码应该引发警报"1",但不执行任何操作.

window.onpopstate = function(event) { alert(event.state.a) }
history.pushState({a: 1})
history.back()
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/WNurW/2/

有任何想法吗?

And*_*ock 12

你的代码不会导致popstate,因为pushstate命令告诉你现在在哪个页面.

window.onpopstate = function(event) { alert(event.state.a) }
history.pushState({a: 1});
history.pushState({a: 2});
history.back()
Run Code Online (Sandbox Code Playgroud)

上面的代码将起作用.
继承人:http://jsfiddle.net/WNurW/8/

HTML5历史

正如您在上面的图片中看到的那样:
(1)在这里您输入了页面或小提琴,然后您想要pushState,这将添加一个到历史链的新链接.

(2)当您按下状态时,您将再添加一次回溯到历史记录,但它也会将"历史记录"中的当前位置移动到新状态.所以回去,不会给你你认为你得到的历史状态,它会给你前一个.

(3)您必须转到"新"页面或推送另一个历史状态,才能返回到您在步骤(2)中创建的状态.

  • 我要做的另一点是传递给popstate的event.state不是我们刚刚弹出的状态,而是新安装的状态. (3认同)
  • 很好的解释,喜欢这个图表! (2认同)

fel*_*ins 5

为了强制触发事件,您需要在同一文档的两个历史记录条目之间导航并调用正确的历史记录方法.
只调用history.pushState()history.replaceState(),它不会触发popstate事件.另外,检查history.pushState()参数.

所以你可以这样做:

window.onpopstate = function(event) { alert(event.state.a) }
history.pushState({a: 1}, "")
history.back() //add history entry
history.back() //add history entry
history.go(1)
Run Code Online (Sandbox Code Playgroud)

这里更精心:)

<!DOCTYPE html>
<html>
<head>
    <title>page</title>
</head>
<body>

<script type="application/x-javascript">

function changeState(){
    history.pushState({page: 1}, "page title", "?page=1");
    history.pushState({page: 2}, "other title ", "?page=2");
    //replaceState: Updates the most recent entry on the history stack
    history.replaceState({page: 3}, "title 3", "?page=3");
    history.back(); 
    history.back(); 
    history.go(2); 
}

function showState(event){
    var restultState = JSON.stringify(event.state)
    alert("location: " + document.location + ", state: " + restultState);
}

window.onpopstate = showState;
changeState();

</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)