Popstate - passing popped state to event handler

前端 未结 3 1465
误落风尘
误落风尘 2021-01-02 08:26

The following code should cause an alert of \'1\', but instead does nothing.

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


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-02 09:17

    Your code woudn't cause a popstate, as the pushstate command tells what page you are on NOW.

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

    The above code will work.
    Heres the fiddle: http://jsfiddle.net/WNurW/8/

    HTML5 History

    As you can see on the above picture:
    (1) Here you entered the page, or the fiddle, you then want to pushState, which will add a new link to the history chain.

    (2) When you push state, you will add one more back click to the history, but it will also move the current place in "history" up to your new state. So going back, will not give you the history state you think you are getting, it will give the previous one.

    (3) You have to go to a "new" page, or push another history state, to be able to go back to the state you created in step (2).

提交回复
热议问题