返回上一級頁面

需求重現

頁面跳轉時,點擊返回有時會陷入循環,無法逐級向上返回

解決辦法
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();

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章