我有一个JQGrid,其中填充的数据可以正常工作。默认排序功能正在按预期方式工作。不过,我想按一下[点击]栏,再按[名称]栏排序;每次。我认为onSortCol是我应该开始的地方,但是文档中关于如何对表内容进行排序的内容并不多。理想情况下,我不想不必编写自己的排序算法,而只需以某种方式插入JQGrid API。所有数据都在客户端上,我希望尽可能避免访问服务器。

这是我用来创建网格的代码:

$jqGrid = $('#people_SelectedContacts').jqGrid({
    ajaxGridOptions: {
        type: "POST"
    },
    url: 'AJAX/GetContacts',
    datatype: "json",
    postData: JSON.stringify({ ID: $('#ID').val() }),
    loadonce: true,
    sortable: true,
    caption: "Selected Contacts",
    hidegrid: false,
    autowidth: true,
    rowNum: 10000,
    height: "100%",
    loadui: 'block',
    colNames: ['lecID', 'lrlID', 'mjID', 'Role', 'Name', 'Entity', 'Contact', 'D #', ''],
    colModel: [
        { name: 'LECID', hidden: true },
        { name: 'LRLID', hidden: true },
        { name: 'MJID', hidden: true },
        { name: 'RoleLookupName', index: 'RoleLookupName' },
        { name: 'FullName', index: 'FullName' },
        { name: 'Entity', index: 'Entity' },
        { name: 'ContactInformation', index: 'ContactInformation' },
        { name: 'DNumber', index: 'DNumber' },
        { name: 'Remove', sortable: false, width: 25 }
    ],
    jsonReader: {
        root: 'ReturnValues.Contacts',
        repeatitems: false
    },
    beforeProcessing: function (data, status, xhr) {
        if (!data.ReturnValues.Contacts) {
            data.ReturnValues.Contacts = new Array();
        }
        $.each(data.ReturnValues.Contacts, function (index, value) {
            value.Entity = FormatAddress(value);
            value.ContactInformation = FormatContact(value);
            value.DNumber = FormatDocket(value);
        });
    },
    gridComplete: function () {
        var ids = $jqGrid.jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            removeButton = $('<span>').addClass('remove-contact jqui-button-fix');
            $jqGrid.jqGrid('setRowData', ids[i], { Remove: $('<div>').append(removeButton).html() });
        }
    },
    loadComplete: function (data) {

    },
    onSortCol: function (index, iCol, sortorder) {

    }
});

最佳答案

在您的网格中,有5个可见且可排序的列:“RoleLookupName”,“FullName”,“Entity”,“ContactInformation”,“DNumber”。从服务器加载网格数据之后,数据类型将从'json'更改为'local',这与参数loadonce: true的行为相对应。从现在开始,分类将在本地进行。因为您没有在任何列中定义sorttype属性,所以将使用默认的sorttype: 'text'

我如何理解“RoleLookupName”,“Entity”等列中的数据可以包含重复项,因此您希望通过主排序列(例如“RoleLookupName”)和第二列(“全名”)。如果主排序列中有重复项,则网格仍将根据第二列中的第二个条件进行排序。要实现该行为,您应该使用自定义排序。您可以通过将sorttype用作函数来实现它(请参阅the answer)。
sorttype作为函数的想法很简单。 sorttype应该返回字符串或整数,应使用代替主单元格所包含的。例如,您可以如下定义“RoleLookupName”

{ name: 'RoleLookupName', index: 'RoleLookupName',
    sorttype: function (cell, obj) {
        return cell + '_' + obj.FullName;
    }}

包括Another answerthe demo您是否可能也对理解很有兴趣。它展示了更高级的技术,不仅可以实现自定义排序,还可以实现自定义搜索。

10-04 16:15
查看更多