【问题标题】:Popstate - passing popped state to event handlerPopstate - 将弹出状态传递给事件处理程序
【发布时间】:2013-07-23 04:41:45
【问题描述】:

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

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

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

有什么想法吗?

【问题讨论】:

    标签: javascript browser-history


    【解决方案1】:

    您的代码不会导致弹出状态,因为 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) 这里你进入了页面,或者fiddle,然后你想要pushState,这会添加一个新的链接到历史链。

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

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

    【讨论】:

    • 很好的解释,喜欢这个图表!
    • 我要说的另一点是传递给popstate的event.state不是我们刚刚弹出的状态,而是新安装的状态。
    【解决方案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>
    

    【讨论】:

      【解决方案3】:

      在推送新状态之前,您必须修改当前状态。所以,当你回到第一个状态时,你会得到数据:

      // 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";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-30
        • 1970-01-01
        • 1970-01-01
        • 2018-08-03
        • 1970-01-01
        相关资源
        最近更新 更多