因为项目需要对Table进行汇总以及定义列的显示隐藏,所以需要对jQueryUI的TableSorter进行扩展,下面2个插件是我写的,第一个是用显示/隐藏列(右键点击列头会出现右键菜单)。第二个是对列宽度的修正(可以忽略)。第三个是对数据进行汇总,再table footer处会显示汇总列)
Widget的代码:
; (function ($) {
"use strict";
function getColumnsByIndex(table, iColIndex) {
var expression = ':eq(' + iColIndex + ')';
var $table = $(table);
var $items = $table.find("tr").find('td' + expression);
$.merge($items, $table.find('th' + expression));
return $items;
}
function getColumnIndexById(table, colId) {
return $(table).find("th").filter('[data-column-id="' + colId + '"]').index();
}
function getColumnsById(table, colId) {
var index = getColumnIndexById(table, colId);
return getColumnsByIndex(table, index);
}
function ColumnVisibilitySettings() {
this.serialize = function (objSettings) {
return {
version: "1",
visibilities: objSettings
};
};
this.deserialize = function (jsonSettings) {
if (jsonSettings) {
var version = jsonSettings.version;
var objSettings = {};
switch (version) {
case "1":
return jsonSettings.visibilities;
}
}
return undefined;
};
}
$.tablesorter.addWidget({
id: 'column-selector',
priority: 51, // Should be called later than filter
options: {
selector_contextmenu: '.tablesorter-context-menu'
},
m_config: null,
m_widgetOptions: null,
m_settingsLoaded: false,
init: function (table, thisWidget, config, widgetOptions) {
// widget initialization code - this is only *RUN ONCE*
this.m_config = config;
this.m_widgetOptions = widgetOptions;
var self = this;
var $table = config.$table;
$(widgetOptions.selector_contextmenu).hide();
$table.children('thead').bind("contextmenu", $.proxy(this.onShowContextMenu, this));
// setup our event handler
$table.on("save_column_visibility", $.proxy(this.saveColumnVisibility, this));
$table.on("show_context_menu", $.proxy(this.onShowContextMenu, this));
},
format: function (table, config, widgetOptions) {
// widget code to apply to the table *AFTER EACH SORT*
if (!this.m_settingsLoaded) {
this.loadColumnVisibility();
this.m_settingsLoaded = true;
}
},
remove: function (table, config, widgetOptions) {
// do what ever needs to be done to remove stuff added by your widget
// unbind events, restore hidden content, etc.
$table.children('thead').unbind("contextmenu", $.proxy(this.onShowContextMenu, this));
$table.off("save_column_visibility", $.proxy(this.saveColumnVisibility, this));
$table.off("show_context_menu", $.proxy(this.onShowContextMenu, this));
},
onShowContextMenu: function (event, extraEvent) {
// We allow to fack the event
if (extraEvent) event = extraEvent;
event.preventDefault();
var self = this;
var $table = this.m_config.$table;
var $columnsUl = $('<ul></ul>');
var $columns = $table.find("thead>tr>th");
for (var i = 0; i < $columns.length; i++) {
var $column = $($columns[i]);
var columnDisplayName = $column.text();
var columnId