1. 程式人生 > >對pushState、replaceState和onpopstate一點使用

對pushState、replaceState和onpopstate一點使用

listen switch register log rbac url list -s window

應用場景實現點擊瀏覽器前進和回退按鈕importPage,checkPage div區塊的切換

關鍵代碼

  新建tab頁,將頁面url粘貼到地址攔,刷新頁面,此時歷史棧數為2,當前onpopstate事件回調,返回e.state為null,先替換棧裏的當前頁,瀏覽器顯示checkPage頁面,棧裏當前頁也為checkPage。

window.history.replaceState({
wid: ‘checkPage‘
}, document.title);

點擊按鈕,向歷史棧裏添加頁面。

var registerBackPage = function (wid) {
    window.history.pushState({
wid: wid
}, document.title);
}
window.addEventListener("popstate", function (t) {
var wid = "";
if (t.state && t.state.wid) {
wid = t.state.wid;
} else {
return
}
switchPage($(‘#‘ + wid));
})
$("#importPageBtn").click(function () {
registerBackPage(‘importPage‘);
switchPage($(‘#importPage‘));
});

參考鏈接:http://www.cnblogs.com/lyzg/p/5960609.html


對pushState、replaceState和onpopstate一點使用