分析
SlickGrid提供了点击事件方法grid.onClick和grid.onDblClick用于捕获用户对表格列的点击,捕获到点击事件之后,修改表格数据,然后使用grid.updateRow方法将修改后的数据更新到表格中。
展示
代码
创建grid(HTML)
<!--创建grid-->
<div id="myGrid" class="slick-container" style="width:600px;height:500px;"></div>
创建grid(JavaScript)
// 五角星样式
function priorityFormatter(row, cell, value, columnDef, dataContext) {const count = value === 'Low' ? 1 : value === 'Medium' ? 2 : 3;let icon = '';for (let i = 0; i < count; i++) {icon += '<span class="sgi sgi-star-outline"></span>';}return icon;
}var grid;
var data = [];
var columns = [ // 创建columns{id: "title", name: "Title", field: "title", width: 200, cssClass: "cell-title", editor: Slick.Editors.Text},{id: "priority", name: "Priority", field: "priority", width: 80, selectable: false, resizable: false},{id: "priority", name: "Priority", field: "priority", width: 80, selectable: false, resizable: false, formatter: priorityFormatter}
];var options = {editable: true,enableAddRow: false,enableCellNavigation: true,asyncEditorLoading: false,rowHeight: 30
};document.addEventListener("DOMContentLoaded", function() {for (var i = 0; i < 100; i++) { // 创建数据var d = (data[i] = {});d["title"] = "Task " + i;d["priority"] = "Medium";}grid = new Slick.Grid("#myGrid", data, columns, options);
});
注册点击事件
// 注册点击事件
grid.onClick.subscribe(function (e) {var cell = grid.getCellFromEvent(e);if (grid.getColumns()[cell.cell].id == "priority") {if (!grid.getEditorLock().commitCurrentEdit()) {return;}// 修改表格数据var states = {"Low": "Medium", "Medium": "High", "High": "Low"};data[cell.row].priority = states[data[cell.row].priority];grid.updateRow(cell.row); // 将修改后的数据更新到表格e.stopPropagation();}
});
注册双击事件
// 注册双击事件
grid.onDblClick.subscribe(function (e) {var cell = grid.getCellFromEvent(e);if (grid.getColumns()[cell.cell].id == "priority") {if (!grid.getEditorLock().commitCurrentEdit()) {return;}// 修改表格数据var states = {"Low": "Medium", "Medium": "High", "High": "Low"};data[cell.row].priority = states[data[cell.row].priority];grid.updateRow(cell.row); // 将修改后的数据更新到表格e.stopPropagation();}
});