以下代码应该会导致警告'1',但不会执行任何操作。Popstate - 将弹出状态传递给事件处理程序
window.onpopstate = function(event) { alert(event.state.a) }
history.pushState({a: 1})
history.back()
小提琴:http://jsfiddle.net/WNurW/2/
任何想法?
以下代码应该会导致警告'1',但不会执行任何操作。Popstate - 将弹出状态传递给事件处理程序
window.onpopstate = function(event) { alert(event.state.a) }
history.pushState({a: 1})
history.back()
小提琴:http://jsfiddle.net/WNurW/2/
任何想法?
您的代码woudn't导致popstate,作为pushState的命令告诉你在什么页面现在。
window.onpopstate = function(event) { alert(event.state.a) }
history.pushState({a: 1});
history.pushState({a: 2});
history.back()
上述代码将起作用。
继承人的小提琴:http://jsfiddle.net/WNurW/8/
正如你可以在上面的图片中看到:
(1)这里输入的是网页,或小提琴,你再要pushState的,这将添加历史链的新链接。
(2)当您按下状态时,您将为历史添加一个后退单击,但它也会将当前位置以“历史”移动到您的新状态。所以回去后,不会给你你认为你得到的历史状态,它会给出前一个状态。 (3)
(3)您必须转到“新建”页面或推送其他历史状态才能返回到步骤(2)中创建的状态。
为了强制触发事件,您需要在相同文档的两个历史记录条目之间导航并调用适当的历史记录方法。
只需拨打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>
伟大的解释,爱图! –
另一点我会做的是传递给popstate的event.state不是我们刚刚弹出的状态,而是新安装的状态。 –