9

以下代码应该会导致警报“1”,但什么也不做。

window.onpopstate = function(event) { alert(event.state.a) }
history.pushState({a: 1})
history.back()

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

有任何想法吗?

4

3 回答 3

13

您的代码不会导致弹出状态,因为 pushstate 命令会告诉您您现在在哪个页面上。

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

上面的代码将起作用。
这是小提琴:http: //jsfiddle.net/WNurW/8/

HTML5 历史

如上图所示:
(1)这里你进入了页面,或者fiddle,然后你想要pushState,这会在历史链中添加一个新的链接。

(2)当你推送状态时,你会在历史记录中再增加一次后退点击,但它也会将“历史记录”中的当前位置移动到你的新状态。所以回去,不会给你你认为你得到的历史状态,它会给出前一个。

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

于 2013-07-23T07:38:38.367 回答
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)

这里有更详细的内容:)

<!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>
于 2013-07-23T05:47:45.720 回答
0

在推送新状态之前,您必须修改当前状态。因此,当您返回第一个状态时,您将返回数据:

// updating the current state    
window.history.replaceState({a: 1}, "First State", window.location.pathname);
// setting the new state
window.history.pushState({ },"Secound State", window.location.pathname);
// getting the data back
window.onpopstate = (event) => {
  alert(event.state.a); // Displays "1";
}
于 2018-05-30T02:14:59.830 回答