来自 JavaScript 初学者的问题。我有一个用制表器网格创建的表格。我想在单击其中一个单元格时“选择”一列,并取消选择之前选择的另一列。
我当前拥有的代码能够在单击时选择整个列,但取消选择其他列会产生副作用,即另一列会添加到表中(请运行代码片段查看)。我的代码有什么问题吗?还有没有更优雅的方式来取消选择先前选择的列?我不确定将 var selectedCell 保留为全局变量是否是一个好主意。
var tabledata = [
{id:1, fullName:"Oli Bob", age:"12", color:"red"},
{id:2, fullName:"Mary May", age:"1", color:"blue"},
{id:3, fullName:"Christine Lobowski", age:"42", color:"green"},
];
var selectedCell = null;
var table = new Tabulator("#example-table", {
data:tabledata,
columns:[
{title:"Name", field:"fullName"},
{title:"Favourite Color", field:"color"},
],
columnDefaults:{
cellClick:function(e, cell){
if (selectedCell) {
cell.getTable().getColumns().forEach(function (column) {
column.updateDefinition( {cssClass: ""});
});
console.log(" previously selected col " + selectedCell.getColumn().getDefinition().field);
}
selectedCell = cell;
cell.getColumn().updateDefinition({cssClass: "column-selected"});
},
},
});
.column-selected {
color:red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://unpkg.com/[email protected]/dist/css/tabulator.min.css" rel="stylesheet"/>
<script src="https://unpkg.com/[email protected]/dist/js/tabulator.min.js"></script>
</head>
<body>
<div id="example-table"></div>
</body>
</html>
我建议您使用
cellClick
事件根据单击的单元格更新列定义。这是您使用修改后的示例:
const tabledata = [
{ id: 1, fullName: 'Oli Bob', age: '12', color: 'red' },
{ id: 2, fullName: 'Mary May', age: '1', color: 'blue' },
{ id: 3, fullName: 'Christine Lobowski', age: '42', color: 'green' }
]
const table = new Tabulator('#example-table', {
data: tabledata,
columns: [
{ title: 'Name', field: 'fullName' },
{ title: 'Favourite Color', field: 'color' }
]
})
table.on('cellClick', function (e, cell) {
const selectedCol = cell.getColumn().getField()
table.getColumns().forEach((col) => {
col.updateDefinition({ cssClass: col.getField() === selectedCol ? 'column-selected' : '' })
})
})
.column-selected {
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://unpkg.com/[email protected]/dist/css/tabulator.min.css" rel="stylesheet" />
<script src="https://unpkg.com/[email protected]/dist/js/tabulator.min.js"></script>
</head>
<body>
<div id="example-table"></div>
</body>
</html>