必须配且仅配一列 type: 'radio',位置靠左;监听用 table.on('radio(filter)', callback),obj.data 仅含 cols 字段,完整数据需查 table.cache 补全。

必须配 type: 'radio' 列,且只能有一列,否则 table.on('radio(filter)') 根本不触发——不是 bug,是硬性前提。
怎么写 radio 列配置
在 cols 数组里加一列,位置尽量靠左(比如 cols[0]),避免被 fixed: 'left' 列遮挡:
[{ type: 'radio', unresize: true, width: 50 }, { field: 'name', title: '姓名' }]
- 不能写成
type: 'radios'、type: 'Radio'或漏引号,Layui 会直接忽略 - 不能和
{type: 'checkbox'}混用,否则事件失效、UI 错乱,甚至报Cannot read property 'checked' of undefined - 别在
templet里手写<input type="radio">——Layui 渲染时会清空checked属性,导致状态不同步 -
name属性由 Layui 自动统一分配,你不用也不该手动指定
怎么监听选中并拿到数据
用 table.on('radio(filter)', callback),不是 checkbox 事件:
table.on('radio(test)', function(obj) {
console.log(obj.data); // 当前行原始数据(仅含 cols 中定义的字段)
console.log(obj.value); // 该行唯一 ID,默认取 <code>id</code> 或 <code>lay-id</code>
console.log(obj.checked); // 恒为 <code>true</code>,radio 没有“取消”语义
});
- 这个事件只在用户点击 radio 圆点时触发,初始化默认选中、或调用
setRowChecked()时不会自动触发(除非加callbackFlag: true) - 别用
table.checkStatus('test').data[0]取数据——它只返回当前页已勾选的行,而 radio 模式下没有“已勾选集合”概念 - 想拿完整行数据(含未在
cols中定义的字段),得查table.cache['test']并按obj.value匹配
怎么让某行初始就选中
Layui 不支持在原始数据里加 checked: true 驱动 radio 默认选中。必须在 done 回调里手动操作:
table.render({
elem: '#test',
// ...其他配置
done: function() {
// 方法一:通过索引(注意翻页后下标会变)
table.setRowChecked('test', { index: 0, checked: true });
// 方法二:更稳,查 cache 找目标行再设属性(2.8+)
const cache = table.cache['test'];
const target = cache.find(item => item.id === 123);
if (target) {
target['lay-checked'] = 'true';
table.checkStatus('test'); // 强刷 UI
}
}
});
- 不要在
data数组里塞checked: true字段——radio 模式下完全被忽略 - 不要等渲染完再用 jQuery 去
$('input[name=xxx]').prop('checked', true)——Layui 已接管事件绑定,极易错位 - 如果表格启用了分页,
table.cache存的是所有已加载页的数据,不是当前页;跨页默认选中需自己维护 ID 映射逻辑
最易被忽略的一点:obj.data 里永远只有 cols 中声明过的字段,哪怕原始 JSON 里有 extra_info、create_time 这类字段,也不会自动带上。要完整对象,必须查 table.cache 补全——这点在调试时经常卡人很久。











