如何在jqgrid中保留当前行 [英] how to persist current row in jqgrid

查看:29
本文介绍了如何在jqgrid中保留当前行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果再次打开网格或刷新页面,如何保留当前行?

的代码关于使用 another answer 的代码保留 jqGrid 列首选项,其中我建议了实现持久选择行的代码.值得一提的是,在 multiselect:true 的情况下,它将使用包含所有选定行的 ids 数组,其中包含所有选定的行,即使这些行在另一个页面上.它非常实用,实现非常简单.所以我发布了相应的 功能请求,但直到现在仍未得到答复.

现在我可以展示两个演示:第一个演示使用 multiselect: true第二个演示 它使用相同的代码,但只有一个选择.

我使用的代码中最重要的部分将在下面找到.

有一点非常重要:您应该在您使用的每个页面中修改 myColumnStateName 的值.变量的值包含 localStorage 中列状态的名称.因此,如果您不会更改名称,您将共享不同表的状态,这可能会产生非常奇怪的效果.您可以考虑使用从当前页面的名称或其 URL 构造的名称作为 myColumnStateName 的值.

var $grid = $("#list"),getColumnIndex = function (grid, columnIndex) {var cm = grid.jqGrid('getGridParam', 'colModel'), i, l = cm.length;对于 (i = 0; i < l; i++) {if ((cm[i].index || cm[i].name) === columnIndex) {返回我;//返回 colModel 索引}}返回-1;},refreshSerchingToolbar = function ($grid, myDefaultSearch) {var postData = $grid.jqGrid('getGridParam', 'postData'), 过滤器, i, l,规则, 规则, iCol, cm = $grid.jqGrid('getGridParam', 'colModel'),cmi,控制,标签名;for (i = 0, l = cm.length; i < l; i++) {控制 = $("#gs_" + $.jgrid.jqID(cm[i].name));if (control.length > 0) {tagName = control[0].tagName.toUpperCase();if (tagName === "SELECT") {//&&cmi.stype === "选择"control.find("option[value='']").attr('选中', '选中');} else if (tagName === "INPUT") {control.val('');}}}if (typeof (postData.filters) === "string" &&typeof ($grid[0].ftoolbar) === "boolean" &&$grid[0].ftoolbar) {过滤器 = $.parseJSON(postData.filters);if (filters && filters.groupOp === "AND" && typeof (filters.groups) === "undefined") {//仅在没有分组的情况下进行高级搜索,我们在//搜索工具栏规则=过滤器.规则;for (i = 0, l = rules.length; i < l; i++) {规则=规则[i];iCol = getColumnIndex($grid, rule.field);如果 (iCol >= 0) {cmi = cm[iCol];控制 = $("#gs_" + $.jgrid.jqID(cmi.name));if (control.length > 0 &&(((typeof (cmi.searchoptions) === "未定义" ||typeof (cmi.searchoptions.sopt) === "未定义")&&rule.op === myDefaultSearch) ||(typeof (cmi.searchoptions) === "object" &&$.isArray(cmi.searchoptions.sopt) &&cmi.searchoptions.sopt.length >0&&cmi.searchoptions.sopt[0] === rule.op))) {tagName = control[0].tagName.toUpperCase();if (tagName === "SELECT") {//&&cmi.stype === "选择"control.find("option[value='" + $.jgrid.jqID(rule.data) + "']").attr('选中', '选中');} else if (tagName === "INPUT") {control.val(rule.data);}}}}}}},saveObjectInLocalStorage = function (storageItemName, object) {if (typeof window.localStorage !== 'undefined') {window.localStorage.setItem(storageItemName, JSON.stringify(object));}},removeObjectFromLocalStorage = function (storageItemName) {if (typeof window.localStorage !== 'undefined') {window.localStorage.removeItem(storageItemName);}},getObjectFromLocalStorage = function (storageItemName) {if (typeof window.localStorage !== 'undefined') {返回 JSON.parse(window.localStorage.getItem(storageItemName));}},myColumnStateName = 'ColumnChooserAndLocalStorage2.colState',idsOfSelectedRows = [],saveColumnState = function (perm) {var colModel = this.jqGrid('getGridParam', 'colModel'), i, l = colModel.length, colItem, cmName,postData = this.jqGrid('getGridParam', 'postData'),列状态 = {搜索:this.jqGrid('getGridParam', 'search'),页面:this.jqGrid('getGridParam', 'page'),排序名称:this.jqGrid('getGridParam', 'sortname'),排序顺序:this.jqGrid('getGridParam', 'sortorder'),排列:烫发,selectedRows:idsOfSelectedRows,colStates:{}},colStates = 列状态.colStates;if (typeof (postData.filters) !== 'undefined') {columnsState.filters = postData.filters;}对于 (i = 0; i < l; i++) {colItem = colModel[i];cmName = colItem.name;if (cmName !== 'rn' && cmName !== 'cb' && cmName !== 'subgrid') {colStates[cmName] = {宽度:colItem.width,隐藏:colItem.hidden};}}saveObjectInLocalStorage(myColumnStateName, columnsState);},我的列状态,isColState,restoreColumnState = function (colModel) {var colItem, i, l = colModel.length, colStates, cmName,columnsState = getObjectFromLocalStorage(myColumnStateName);如果(列状态){colStates = 列状态.colStates;对于 (i = 0; i < l; i++) {colItem = colModel[i];cmName = colItem.name;if (cmName !== 'rn' && cmName !== 'cb' && cmName !== 'subgrid') {colModel[i] = $.extend(true, {}, colModel[i], colStates[cmName]);}}}返回列状态;},updateIdsOfSelectedRows = function (id, isSelected) {var index = idsOfSelectedRows.indexOf(id);if (!isSelected && index >= 0) {idsOfSelectedRows.splice(index, 1);//从列表中删除 id} else if (index < 0) {idsOfSelectedRows.push(id);}},首次加载 = 真;myColumnsState = restoreColumnState(cm);isColState = typeof (myColumnsState) !== '未定义' &&myColumnsState !== null;idsOfSelectedRows = isColState &&typeof(myColumnsState.selectedRows)!==未定义"?myColumnsState.selectedRows : [];$grid.jqGrid({//... 一些选项页: isColState ?myColumnsState.page : 1,搜索:isColState ?myColumnsState.search:假,postData: isColState ?{过滤器:myColumnsState.filters}:{},排序名称:isColState ?myColumnsState.sortname : 'invdate',排序顺序:isColState ?myColumnsState.sortorder : 'desc',onSelectRow: 函数 (id, isSelected) {updateIdsOfSelectedRows(id, isSelected);saveColumnState.call($grid, $grid[0].p.remapColumns);},onSelectAll:函数(aRowids,isSelected){变量我,计数,ID;for (i = 0, count = aRowids.length; i < count; i++) {id = aRowids[i];updateIdsOfSelectedRows(id, isSelected);}saveColumnState.call($grid, $grid[0].p.remapColumns);},加载完成:函数(){var $this = $(this), i, count;如果(第一次加载){首次加载 = 假;如果(isColState){$this.jqGrid("remapColumns", myColumnsState.permutation, true);}if (typeof (this.ftoolbar) !== "boolean" || !this.ftoolbar) {//如果需要,创建工具栏$this.jqGrid('filterToolbar',{stringResult: true, searchOnEnter: true, defaultSearch: myDefaultSearch});}}refreshSerchingToolbar($this, myDefaultSearch);for (i = 0, count = idsOfSelectedRows.length; i < count; i++) {$this.jqGrid('setSelection', idsOfSelectedRows[i], false);}saveColumnState.call($this, this.p.remapColumns);},调整停止:函数(){saveColumnState.call($grid, $grid[0].p.remapColumns);}});$grid.jqGrid('navGrid', '#pager', {edit: false, add: false, del: false});$grid.jqGrid('navButtonAdd', '#pager', {标题: "",buttonicon: "ui-icon-closethick",title: "清除保存的网格设置",onClickButton: 函数 () {removeObjectFromLocalStorage(myColumnStateName);window.location.reload();}});

更新:我忘了提一下,在 jqGrid 4.3 中使用 multiselect: true 选项时,使用 修复 这里描述的.在第一个演示中,我使用了 jquery.jqGrid.src.js 的修改版本,其中包含错误修复.

更新 2:为了方便生成用于保存网格状态的本地存储项的唯一名称,我对演示进行了一些修改.多选演示单选演示使用myColumnStateName作为函数定义如下

var myColumnStateName = function (grid) {返回 window.location.pathname + '#' + grid[0].id;}

myColumnStateName 的用法也相应改变.此外,我扩展了列状态以保存 rowNum 值.

更新 3: 答案 描述如何使用免费 jqGrid 的新可能性保存网格状态.

How to presist current row if grid is opened again or page is refreshed ?

Answer in Persisting jqGrid column preferences describes how to persist column width and some other parameters.

In this answer demo I clicked in some row and pressed F5 . Previous clicked row was not highlighted. How to save / restore current row in local storage ?

Update

If jqGrid column structure is modified in application and user opens application from browser again, restorecolumnstate creates invalid colmodel where some elements are missing. This causes exception in refreshSearchingToolbar which assumes that all colmodel elements are present.

How to fix this ? How to dedect modified colmodol and not to restore colmodel in this case ? Or should restoreColumnState update colModel so that proper array is created ?

**Update 2 **

If myColumnsState.permutation contains nulls $grid.jqGrid("remapColumns", myColumnsState.permutation, true) created invalid colmodel. Here are screenshots from VS debugger immediately before and after remapColumns call

after:

I fixed this by chaning code to

    if (isColState && myColumnsState.permutation.length > 0) {
        var i, isnull = false;
        for (i = 0; i < myColumnsState.permutation.length; i = i + 1) {
            if (myColumnsState.permutation[i] == null) {
                isnull = true;
                break;
            }
        }
        if (!isnull) {
            $grid.jqGrid("remapColumns", myColumnsState.permutation, true);
        }

Is this best solution ?

解决方案

I combined the code from the previous answer about persisting jqGrid column preferences with the code of from another answer where I suggested the code which implemented persistent selection of rows. It's important to mention, that in case of multiselect:true it will be used the array of ids of selected rows which contains all selected even if the rows are on another page. It's very practical and the implementation very simple. So I posted the corresponding feature request, but it's stay till now unanswered.

Now I can present two demos: the first demo which use multiselect: true and the second demo which uses the same code, but with the single selection.

The most important parts of the code which I used you will find below.

One thing is very important to mention: you should modify the value of myColumnStateName in every page which you use. The value of the variable contain the name of the column state in the localStorage. So it you would not change the name you will share state of different tables which can follows to very strange effects. You can consider to use names constructed from the name of the current page or it's URL as the value of myColumnStateName.

var $grid = $("#list"),
    getColumnIndex = function (grid, columnIndex) {
        var cm = grid.jqGrid('getGridParam', 'colModel'), i, l = cm.length;
        for (i = 0; i < l; i++) {
            if ((cm[i].index || cm[i].name) === columnIndex) {
                return i; // return the colModel index
            }
        }
        return -1;
    },
    refreshSerchingToolbar = function ($grid, myDefaultSearch) {
        var postData = $grid.jqGrid('getGridParam', 'postData'), filters, i, l,
            rules, rule, iCol, cm = $grid.jqGrid('getGridParam', 'colModel'),
            cmi, control, tagName;

        for (i = 0, l = cm.length; i < l; i++) {
            control = $("#gs_" + $.jgrid.jqID(cm[i].name));
            if (control.length > 0) {
                tagName = control[0].tagName.toUpperCase();
                if (tagName === "SELECT") { // && cmi.stype === "select"
                    control.find("option[value='']")
                        .attr('selected', 'selected');
                } else if (tagName === "INPUT") {
                    control.val('');
                }
            }
        }

        if (typeof (postData.filters) === "string" &&
                typeof ($grid[0].ftoolbar) === "boolean" && $grid[0].ftoolbar) {

            filters = $.parseJSON(postData.filters);
            if (filters && filters.groupOp === "AND" && typeof (filters.groups) === "undefined") {
                // only in case of advance searching without grouping we import filters in the
                // searching toolbar
                rules = filters.rules;
                for (i = 0, l = rules.length; i < l; i++) {
                    rule = rules[i];
                    iCol = getColumnIndex($grid, rule.field);
                    if (iCol >= 0) {
                        cmi = cm[iCol];
                        control = $("#gs_" + $.jgrid.jqID(cmi.name));
                        if (control.length > 0 &&
                                (((typeof (cmi.searchoptions) === "undefined" ||
                                typeof (cmi.searchoptions.sopt) === "undefined")
                                && rule.op === myDefaultSearch) ||
                                  (typeof (cmi.searchoptions) === "object" &&
                                      $.isArray(cmi.searchoptions.sopt) &&
                                      cmi.searchoptions.sopt.length > 0 &&
                                      cmi.searchoptions.sopt[0] === rule.op))) {
                            tagName = control[0].tagName.toUpperCase();
                            if (tagName === "SELECT") { // && cmi.stype === "select"
                                control.find("option[value='" + $.jgrid.jqID(rule.data) + "']")
                                    .attr('selected', 'selected');
                            } else if (tagName === "INPUT") {
                                control.val(rule.data);
                            }
                        }
                    }
                }
            }
        }
    },
    saveObjectInLocalStorage = function (storageItemName, object) {
        if (typeof window.localStorage !== 'undefined') {
            window.localStorage.setItem(storageItemName, JSON.stringify(object));
        }
    },
    removeObjectFromLocalStorage = function (storageItemName) {
        if (typeof window.localStorage !== 'undefined') {
            window.localStorage.removeItem(storageItemName);
        }
    },
    getObjectFromLocalStorage = function (storageItemName) {
        if (typeof window.localStorage !== 'undefined') {
            return JSON.parse(window.localStorage.getItem(storageItemName));
        }
    },
    myColumnStateName = 'ColumnChooserAndLocalStorage2.colState',
    idsOfSelectedRows = [],
    saveColumnState = function (perm) {
        var colModel = this.jqGrid('getGridParam', 'colModel'), i, l = colModel.length, colItem, cmName,
            postData = this.jqGrid('getGridParam', 'postData'),
            columnsState = {
                search: this.jqGrid('getGridParam', 'search'),
                page: this.jqGrid('getGridParam', 'page'),
                sortname: this.jqGrid('getGridParam', 'sortname'),
                sortorder: this.jqGrid('getGridParam', 'sortorder'),
                permutation: perm,
                selectedRows: idsOfSelectedRows,
                colStates: {}
            },
            colStates = columnsState.colStates;

        if (typeof (postData.filters) !== 'undefined') {
            columnsState.filters = postData.filters;
        }

        for (i = 0; i < l; i++) {
            colItem = colModel[i];
            cmName = colItem.name;
            if (cmName !== 'rn' && cmName !== 'cb' && cmName !== 'subgrid') {
                colStates[cmName] = {
                    width: colItem.width,
                    hidden: colItem.hidden
                };
            }
        }
        saveObjectInLocalStorage(myColumnStateName, columnsState);
    },
    myColumnsState,
    isColState,
    restoreColumnState = function (colModel) {
        var colItem, i, l = colModel.length, colStates, cmName,
            columnsState = getObjectFromLocalStorage(myColumnStateName);

        if (columnsState) {
            colStates = columnsState.colStates;
            for (i = 0; i < l; i++) {
                colItem = colModel[i];
                cmName = colItem.name;
                if (cmName !== 'rn' && cmName !== 'cb' && cmName !== 'subgrid') {
                    colModel[i] = $.extend(true, {}, colModel[i], colStates[cmName]);
                }
            }
        }
        return columnsState;
    },
    updateIdsOfSelectedRows = function (id, isSelected) {
        var index = idsOfSelectedRows.indexOf(id);
        if (!isSelected && index >= 0) {
            idsOfSelectedRows.splice(index, 1); // remove id from the list
        } else if (index < 0) {
            idsOfSelectedRows.push(id);
        }
    },
    firstLoad = true;

myColumnsState = restoreColumnState(cm);
isColState = typeof (myColumnsState) !== 'undefined' && myColumnsState !== null;
idsOfSelectedRows = isColState && typeof (myColumnsState.selectedRows) !== "undefined" ? myColumnsState.selectedRows : [];

$grid.jqGrid({
    // ... some options
    page: isColState ? myColumnsState.page : 1,
    search: isColState ? myColumnsState.search : false,
    postData: isColState ? { filters: myColumnsState.filters } : {},
    sortname: isColState ? myColumnsState.sortname : 'invdate',
    sortorder: isColState ? myColumnsState.sortorder : 'desc',
    onSelectRow: function (id, isSelected) {
        updateIdsOfSelectedRows(id, isSelected);
        saveColumnState.call($grid, $grid[0].p.remapColumns);
    },
    onSelectAll: function (aRowids, isSelected) {
        var i, count, id;
        for (i = 0, count = aRowids.length; i < count; i++) {
            id = aRowids[i];
            updateIdsOfSelectedRows(id, isSelected);
        }
        saveColumnState.call($grid, $grid[0].p.remapColumns);
    },
    loadComplete: function () {
        var $this = $(this), i, count;

        if (firstLoad) {
            firstLoad = false;
            if (isColState) {
                $this.jqGrid("remapColumns", myColumnsState.permutation, true);
            }
            if (typeof (this.ftoolbar) !== "boolean" || !this.ftoolbar) {
                // create toolbar if needed
                $this.jqGrid('filterToolbar',
                    {stringResult: true, searchOnEnter: true, defaultSearch: myDefaultSearch});
            }
        }
        refreshSerchingToolbar($this, myDefaultSearch);
        for (i = 0, count = idsOfSelectedRows.length; i < count; i++) {
            $this.jqGrid('setSelection', idsOfSelectedRows[i], false);
        }
        saveColumnState.call($this, this.p.remapColumns);
    },
    resizeStop: function () {
        saveColumnState.call($grid, $grid[0].p.remapColumns);
    }
});

$grid.jqGrid('navGrid', '#pager', {edit: false, add: false, del: false});
$grid.jqGrid('navButtonAdd', '#pager', {
    caption: "",
    buttonicon: "ui-icon-closethick",
    title: "clear saved grid's settings",
    onClickButton: function () {
        removeObjectFromLocalStorage(myColumnStateName);
        window.location.reload();
    }
});

UPDATED: I forgot to mention that in case of usage multiselect: true option with jqGrid 4.3 it is very important to use the fix which described here. In the first demo I used the modified version of the jquery.jqGrid.src.js which include the bug fix.

UPDATED 2: To make easy to generate unique name of the local storage item used to save the grid state I modified the demos a little. The next version of the multiselect demo and the single select demo use myColumnStateName as the function defined as the following

var myColumnStateName = function (grid) {
        return window.location.pathname + '#' + grid[0].id;
    }

The usage of myColumnStateName are changed correspondingly. Additionally I extended the column state to save the rowNum value.

UPDATED 3: The answer describe how one can use new possibility of free jqGrid to save the grid state.

这篇关于如何在jqgrid中保留当前行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆