首页 > 解决方案 > 如何保存表的状态并在重新加载或新登录后显示它

问题描述

有已实施分页的表格。现在我想在重新加载后保存它的状态,所以每次重新加载后它都不会从第一页开始。我听说过浏览器中的本地存储,但不知道如何在我的情况下实现它。据我了解,我必须在本地保存实际页面的数量并像我的第一页一样加载它:showPage(1); 但取而代之的是“1”,我需要一些变量来包含最后一个活动页面的信息。有人可以帮我吗?

// Returns an array of maxLength (or less) page numbers
// where a 0 in the returned array denotes a gap in the series.
// Parameters:
//   totalPages:     total number of pages
//   page:           current page
//   maxLength:      maximum size of returned array
function getPageList(totalPages, page, maxLength) {
    if (maxLength < 5) throw "maxLength must be at least 5";

    function range(start, end) {
        return Array.from(Array(end - start + 1), (_, i) => i + start);
    }

    var sideWidth = maxLength < 9 ? 1 : 2;
    var leftWidth = (maxLength - sideWidth * 2 - 3) >> 1;// if pageination size=7: res = (7-1*2-3) = 9 and >> 1 = 4 (0,5 falls down)
    var rightWidth = (maxLength - sideWidth * 2 - 2) >> 1;// same like above
    if (totalPages <= maxLength) {
        // no breaks in list
        return range(1, totalPages);
    }
    if (page <= maxLength - sideWidth - 1 - rightWidth) { 
        // no break on left of page
        return range(1, maxLength - sideWidth - 1)
            .concat(0, range(totalPages - sideWidth + 1, totalPages));
    }
    if (page >= totalPages - sideWidth - 1 - rightWidth) {
        // no break on right of page
        return range(1, sideWidth)
            .concat(0, range(totalPages - sideWidth - 1 - rightWidth - leftWidth, totalPages));
    }
    // Breaks on both sides
    return range(1, sideWidth)
        .concat(0, range(page - leftWidth, page + rightWidth),
            0, range(totalPages - sideWidth + 1, totalPages));
}








// Returns the ISO week of the date.
Date.prototype.getWeek = function (y) {
    var date = new Date(this.getTime());
    date.setHours(0, 0, 0, 0);
    // Thursday in current week decides the year.
    if (y == "2021" || y == "2022" || y == "2023" || y == "2027" || y == "2028" || y == "2033" || y == "2034" || y == "2038" || y == "2039" || y == "2044" || y == "2045" || y == "2049" || y == "2050") {
        date.setDate(date.getDate() + 7 - (date.getDay() + 6) % 7);
    }
    else {
        date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
    }
    // January 4 is always in week 1.
    var week1 = new Date(date.getFullYear(), 0, 4);
    // Adjust to Thursday in week 1 and count number of weeks from date to week1.
    return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}

function getDateRangeOfWeek(weekNo, y) {
    var d1, numOfdaysPastSinceLastMonday, i;
    var dates = [];

    for (i = 0; i < 7; i++) {

        d1 = new Date('' + y + '');

        numOfdaysPastSinceLastMonday = d1.getDay() - 1;
        d1.setDate(d1.getDate() - numOfdaysPastSinceLastMonday);
        d1.setDate(d1.getDate() + (7 * (weekNo - d1.getWeek(y))));
        d1.setDate(d1.getDate() + i);
        let item = d1.getDate() + "." + (d1.getMonth() + 1) + "." + d1.getFullYear();
        dates.push(item);
    }

    return dates;

};











var tableId = "Tabledta";


function LoadData() {
    var tab = $("<table  id=calendar class=MyTable border=1></table>");
    var thead = $("<thead></thead>");
    var tbody = $('<tbody id="jar"></tbody>');

    var theadrow = $("<tr/>")
    theadrow.append('<th style="padding:5px;font-weight:bold;">FSE' + "&nbsp;" + '</th>');
    theadrow.append('<th style="padding:5px;font-weight:bold;">Monday' + "&nbsp;" + '</th>');
    theadrow.append('<th style="padding:5px;font-weight:bold;">Tuesday' + "&nbsp;" + '</th>');
    theadrow.append('<th style="padding:5px;font-weight:bold;">Wednesday' + "&nbsp;" + '</th>');
    theadrow.append('<th style="padding:5px;font-weight:bold;">Thursday' + "&nbsp;" + '</th>');
    theadrow.append('<th style="padding:5px;font-weight:bold;">Friday' + "&nbsp;" + '</th>');
    theadrow.append('<th style="padding:5px;font-weight:bold;">Saturday' + "&nbsp;" + '</th>');
    theadrow.append('<th style="padding:5px;font-weight:bold;">Sunday' + "&nbsp;" + '</th>');
    thead.append(theadrow);





    for (var i = 1; i < 521; i++) {

        var trow = $("<tr class=content/>").data("id", i);                                //.data("id", i, "class", "content");
        trow.append("<td>FSE" + i + "</td>");
        trow.append("<td>Monday" + i + "</td>");
        trow.append("<td>Tuesday" + i + "</td>");
        trow.append("<td>Wednesday" + i + "</td>");
        trow.append("<td> Thursday" + i + "</td>");
        trow.append(" <td>Friday" + i + "</td>");
        trow.append("<td>Saturday" + i + "</td>");
        trow.append("<td>Sunday" + i + "</td>");
        tbody.append(trow);
    }


    tab.append(thead);
    tab.append(tbody);
    $("#" + tableId).html(tab);
}



// Below is an example use of the above function.
$(function () {

    LoadData();
    

     let week = 1;

    $("#calendar tbody tr").each(function () {
        let count = $(this).index();
        if (count % 11 === 0) {
            let items = getDateRangeOfWeek(week, 2020);
            let newrow = "<tr class='content'><td></td><td>" + items[0] + "</td><td>" + items[1] + "</td><td>" + items[2] + "</td><td>" + items[3] + "</td><td>" + items[4] + "</td><td>" + items[5] + "</td><td>" + items[6] + "</td></tr>";
            if (count === 0) {
                $(newrow).insertBefore("#calendar tbody tr:eq(" + (count) + ")");
            }
            else{
                $(newrow).insertAfter("#calendar tbody tr:eq(" + (count - 1) + ")");
            }
            week += 1;
        }
    });

    // Number of items and limits the number of items per page
    var numberOfItems = $("#jar .content").length;
    var limitPerPage = 11;
    // Total pages rounded upwards
    var totalPages = Math.ceil(numberOfItems / limitPerPage);
    // Number of buttons at the top, not counting prev/next,
    // but including the dotted buttons.
    // Must be at least 5:
    var paginationSize = 7;
    var currentPage;

    function showPage(whichPage) {

        if (whichPage < 1 || whichPage > totalPages) return false;
        currentPage = whichPage;
        $("#jar .content").hide()
            .slice((currentPage - 1) * limitPerPage,
                currentPage * limitPerPage).show();
        // Replace the navigation items (not prev/next):            
        $(".pagination li").slice(1, -1).remove();
        getPageList(totalPages, currentPage, paginationSize).forEach(item => {
            $("<li>").addClass("page-item")
                .addClass(item ? "current-page" : "disabled")
                .toggleClass("active", item === currentPage).append(
                    $("<a>").addClass("page-link").attr({
                        href: "javascript:void(0)"
                    }).text(item || "...")
                ).insertBefore("#next-page");
        });
        // Disable prev/next when at first/last page:
        $("#previous-page").toggleClass("disabled", currentPage === 1);
        $("#next-page").toggleClass("disabled", currentPage === totalPages);
        return true;

    }

    // Include the prev/next buttons:
    $(".pagination").append(
        $("<li>").addClass("page-item").attr({ id: "previous-page" }).append(
            $("<a>").addClass("page-link").attr({
                href: "javascript:void(0)"
            }).text("Prev")
        ),
        $("<li>").addClass("page-item").attr({ id: "next-page" }).append(
            $("<a>").addClass("page-link").attr({
                href: "javascript:void(0)"
            }).text("Next")
        )
    );
    // Show the page links
    $("#jar").show();
    showPage(1);

    //$("#jar .content").hide()
    //    .slice((currentPage - 1) * limitPerPage,
    //        currentPage * limitPerPage).show();




    ////Activating of the first page
    //function rowDisplay(startIndex, endIndex) {
    //    $('#jar tr').hide().slice(startIndex, endIndex).show();
        
    //}
    //showPage(1);

    // Use event delegation, as these items are recreated later    
    $(document).on("click", ".pagination li.current-page:not(.active)", function () {
        return showPage(+$(this).text());

        //var pageNumber = $(this).text().trim();
        //savePage(tableId, pageNumber);

    });
    $("#next-page").on("click", function () {
        return showPage(currentPage + 1);
    });

    $("#previous-page").on("click", function () {
        return showPage(currentPage - 1);

    });


    



});


// save status of the page
// use the id of the table, in case multiple tables present
//function savePage(tableId, pageId) {
//    localStorage.setItem(tableId, pageId);
//}

//function LoadData(tableId) {
//    return localStorage.getItem(tableId);
//}

//function setPageId(tableId) {
//    var item = LoadData(tableId);

//    if (!item) {
//        return;
//    }

//    $(".active").removeClass("active");
//    var $pageButton = $('#pagination li:contains("' + item + '")');

//    if (!$pageButton) {
//        return;
//    }

//    var pageData = $pageButton.data();
//    rowDisplay(pageData.start, pageData.end);
//}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">



<div id="Tabledta"></div>
<div class="pagination"></div>

标签: javascriptjsonpagination

解决方案


您可以使用以下两种方法,

  1. sessionStorage 在此处查看文档

在您的情况下,我建议使用sessionStorage,因为仅对当前会话有效。将最新的页码保存到 sessionStorage。并在页面刷新后检查 sessionStorage 中是否存在该值

var currentPage = sessionStorage.getItem('currentPage');
if(!currentPage) {
 currentPage = 1;
}
showPage(currentPage);

---保存到会话存储

sessionStorage.setItem('currentPage', page);

--- 从 sessionStorage 获取数据

var page = sessionStorage.getItem('currentPage');
  1. localStorage 即使浏览器关闭,请参阅此处的文档。

推荐阅读