1. 程式人生 > >返回上一級頁面

返回上一級頁面

需求重現

頁面跳轉時,點選返回有時會陷入迴圈,無法逐級向上返回

解決辦法
js檔案

var historyUtils = {
    add : function (url) {
        var historyArray = historyUtils.getLocal();
        if (!historyArray) {
            historyArray = [];
        }
        var currentPage = historyArray.pop();
        if (currentPage && currentPage == url) {
            //do nothing
} else if (currentPage){ historyArray.push(currentPage); //歷史裡面沒有現在傳入的url,在加回去 } historyArray.push(url); historyUtils.saveLocal(historyArray); }, back : function() { var historyArray = historyUtils.getLocal(); var currentPage = historyArray.pop();//去掉當前頁面,pop取最後,類似stack
var history = historyArray.pop(); if (!history) {//沒有歷史頁面 historyUtils.add(currentPage);//將當前頁面加入回陣列中 return; } historyUtils.saveLocal(historyArray); window.location.href = history; }, getLocal : function() { var result = window.sessionStorage.getItem(historyUtils.key); if
(!result) { return null; } return JSON.parse(result); }, saveLocal : function(data) { window.sessionStorage.setItem(historyUtils.key, JSON.stringify(data)); }, init : function() { historyUtils.saveLocal([]); }, key : "_history_" }; historyUtils.add(window.location.href);

使用:只需在每個頁面引入此js,向上級返回時用下述方法即可:

historyUtils.back();

這樣就可以了!僅供參考!