今天维护以前老项目时,碰到需要监听获取bootstrap-table CheckBox 的选中和取消事件,并做不同的处理,找了会才试出正确的方法,特此记录下。
因为当前业务是需要选中立即提交,所以就不能用选中后获取当前所有选中的行批量提交的方式,只能是单条选中/取消实时请求接口。
//获取当前选中的行对象
$("#dataGrid").on("check.bs.table", function (e, row, $element) { //点击CheckBox触发事件
//row - 当前的行对象,取值方式 row.属性
var _memberId = row.memberId;
//省略访问后台逻辑
});
其中 $("#dataGrid") 为当前table对象
//获取当前取消选中的行对象
$("#dataGrid").on("uncheck.bs.table", function (e, row, $element) {
//row - 当前的行对象,取值方式 row.属性
var _memberId = row.memberId;
//省略访问后台逻辑
});
//设置CheckBox默认选中
[[
{field: 'ck', checkbox: true, align: 'center',formatter: function(value, row, index){
var _checked = false; //默认不选中
if(!u.isEmpty(row.authDate)){ //满足条件,设置选中
_checked = true;
};
return {
checked: _checked
}
}},
{field: 'account', title: '会员邮箱', align: 'center'},
{field: 'authDate', title: '授权时间', align: 'center'},
]]
上述代码片段为初始化bootstrap-table时对列属性 columns 的设置,其中第一个对象 field:'ck' 为第一列 CheckBox 列表,全部列效果如 文中第一张图片。