今天,后台中需要新增一个功能,用户可以自由选择显示的列,之后保存到本地localStroage中。所以扩展了easyui中datagrid的onHeaderContextMenu方法。

使用方法:

复制代码
 _this.$table.datagrid(_.extend({
                    fit: true,
                    border: false,
                    striped: true,
                    method: "get",
                    pagination: true,
                    singleSelect: true,
                    loadMsg: "加载数据中...",
                    columns: _this.getTableColumns(),
                    onResize: function () {
                        if (_this.$ajaxDialog) {
                            _this.$ajaxDialog.dialog("restore");
                            _this.$ajaxDialog.dialog("maximize");
                        }
                    },
                    onSelect: function (rowIndex, rowData) {
                        _this.currentRow = rowData;
                        _this.currentRowIndex = rowIndex;
                        _this.toolbarViewModel.disabled(false);
                    },
                    onLoadError: function () {
                        // $.messager.alert("提示", "服务器忙,请稍后再试!", "warning");
                    },
                    onHeaderContextMenu: function (e, field) {
                        $.fn.easyuiExtension.showHideColumns(_this.$table, {
                            left: e.clientX,
                            top: e.clientY
                        });
                        e.preventDefault();
                    },
                    onRowContextMenu: function (e, rowIndex, rowData) {
                        e.preventDefault();
                        $(this).datagrid("unselectAll");
                        $(this).datagrid("selectRow", rowIndex);

                        if (_this.$menu) {
                            _this.$menu.menu("show", {
                                left: e.pageX,
                                top: e.pageY
                            });
                        }
                    }
                }, options));
复制代码 复制代码
$.fn.easyuiExtension = {
                showHideColumns: function ($table, position) {
                    var $menus = $(document.createElement("div"));
var canClick = true, nonHiddenCount = 0;
var columnsFields = $table.datagrid("getColumnFields"),
columns = [],
columsDetail;

for (var i in columnsFields) {
columsDetail = $table.datagrid("getColumnOption", columnsFields[i]);
columns.push(columsDetail);
}

if (columns.length) {
$menus.menu({
hideOnUnhover: false,
duration: 200,
onHide: function () {
setTimeout(function () {
$menus.menu("destroy");
}, 200);
},
onClick: function (item) {
if (canClick || !item.iconCls) {
$table.datagrid((item.iconCls ? "hideColumn" : "showColumn"), item.id);
}
}
});

for (var i in columns) {
var item = columns[i];
!item.hidden && nonHiddenCount++;
$menus.menu("appendItem", {
text: item.title,
id: item.field,
iconCls: item.hidden ? "" : "icon-ok"
});
}
canClick = nonHiddenCount > 1;
$menus.menu("show", position); } } };
复制代码

效果如下:

\