如何在Tabulator表格中添加单选按钮作为rowFormatter?现有代码无效
解决Tabulator表格添加单选按钮的问题
方法一:配置表格单选模式 + 自带rowSelection格式化器
单独设置列的rowSelection formatter不会生效,因为该格式化器依赖表格的选择功能配置,必须在表格初始化时开启单选模式:
完整示例代码:
// 初始化表格 const table = new Tabulator("#example-table", { columns: [ { title:"#", formatter:"rowSelection", titleFormatter: "", hozAlign:"center", headerSort:false, width:60, minWidth:60, frozen: true }, // 其他列配置示例 { title: "姓名", field: "name" }, { title: "年龄", field: "age" } ], // 关键配置:开启单选模式 selectable: 1, // 可选:允许点击行本身触发单选 selectableRows: true });
方法二:自定义单选按钮格式化器
如果不想依赖Tabulator自带的选择功能,可以自定义formatter手动渲染单选按钮并控制选中逻辑:
示例代码:
const table = new Tabulator("#example-table", { columns: [ { title:"#", hozAlign:"center", headerSort:false, width:60, minWidth:60, frozen: true, // 自定义格式化器 formatter:function(cell, formatterParams, onRendered){ const radio = document.createElement("input"); radio.type = "radio"; radio.name = "row-radio"; // 统一name保证单选逻辑 radio.value = cell.getRow().getData().id; // 初始化选中状态 if(cell.getRow().getData().selected){ radio.checked = true; } // 绑定选中事件,同步所有行状态 radio.addEventListener("change", function(){ table.getRows().forEach(row => row.update({selected: false})); cell.getRow().update({selected: true}); }); return radio; } }, // 其他列示例 { title: "姓名", field: "name" }, { title: "年龄", field: "age" } ], // 示例数据 data: [ {id:1, name:"张三", age:25, selected: false}, {id:2, name:"李四", age:30, selected: true}, {id:3, name:"王五", age:28, selected: false} ] });
常见排查点
- 确认Tabulator版本在4.0以上,
rowSelectionformatter是该版本后新增的功能; - 检查是否误将表格的
selectable设为false,这会直接禁用选择功能; - 自定义格式化器时,确保行数据的
selected字段与单选按钮状态同步,避免DOM渲染后状态不一致。
内容的提问来源于stack exchange,提问作者Ankit Jain
相关产品推荐
相关产品推荐

