您现在的位置:首页 >> 前端 >> 内容

bootstraptable实现x-editable的行单元格编辑及解决数据Empty和支持多样式

时间:2017/8/11 9:46:00 点击:

  核心提示:前言最近在研究bootstrap table的表格的单元格编辑功能,实现点击单元格修改内容,其中包括文本(text)方式修改,下拉选择(select)方式修改,日期(date)格式修改等。 本文着重解...

前言

最近在研究bootstrap table的表格的单元格编辑功能,实现点击单元格修改内容,其中包括文本(text)方式修改,下拉选择(select)方式修改,日期(date)格式修改等。 本文着重解决x-editable编辑的数据动态添加和显示数据为Empty的问题,还有给表格单元格的内容设置多样式,使得显示多样化。 由于官网给的demo的数据都是html文件里写好的,select类型的不能动态添加(所以网上的大多都是官网的类似例子,本篇博客就是在这种情况下以自己的经验分享给大家,有问题可以留言哦),一旦动态添加就会出现显示数据为Empty,我表格原本是有数据的,但是一用这个插件就把数据变成Empty了,这可不是我想要的,所以笔者就自行解决了这个问题。

对比网上的例子

比如以下这种数据不是Empty的例子,但是是由于在html中写死了数据(awesome),不适合动态添加。

awesome
<script>
$(function(){
    $('#username').editable({
        url: '/post',
        title: 'Enter username'
    });
});
</script>
另外一种就是使用bootstrap table动态添加的,但是select类型就会出现数据为Empty的情况。
$('#db_dependences').bootstrapTable({
        method:'POST',
        dataType:'json',
        contentType: "application/x-www-form-urlencoded",
        cache: false,
        striped: true,                       //是否显示行间隔色
        sidePagination: "client",           //分页方式:client客户端分页,server服务端分页(*)
        showColumns:true,
        pagination:true,
        minimumCountColumns:2,
        pageNumber:1,                       //初始化加载第一页,默认第一页
        pageSize: 10,                       //每页的记录行数(*)
        pageList: [10, 15, 20, 25],        //可供选择的每页的行数(*)
        uniqueId: "id",                     //每一行的唯一标识,一般为主键列
        showExport: true,                    
        exportDataType: 'all',
        exportTypes:[ 'csv', 'txt', 'sql', 'doc', 'excel', 'xlsx', 'pdf'],  //导出文件类型
        onEditableSave: function (field, row, oldValue, $el) {
            $.ajax({
                success: function (data, status) {
                    if (status == "success") {
                        alert("编辑成功");
                    }
                },
                error: function () {
                    alert("Error");
                },
                complete: function () {

                }
            });
        },
        data: [{
            id: 1,
            name: '张三',
            sex: '男',
            time: '2017-08-09'
        }, {
            id: 2,
            name: '王五',
            sex: '女',
            time: '2017-08-09'
        }, {
            id: 3,
            name: '李四',
            sex: '男',
            time: '2017-08-09'
        }, {
            id: 4,
            name: '杨朝来',
            sex: '男',
            time: '2017-08-09'
        }, {
            id: 5,
            name: '蒋平',
            sex: '男',
            time: '2017-08-09'
        }, {
            id: 6,
            name: '唐灿华',
            sex: '男',
            time: '2017-08-09'
        }],
        columns: [{
            field: 'id',
            title: '序号'
        }, {
            field: 'name',
            title: '姓名',
            editable: {
                type: 'text',  
                validate: function (value) {  
                    if ($.trim(value) == '') {  
                        return '姓名不能为空!';  
                    }  
                }
            } 
        }, {
            field: 'sex',
            title: '性别',
            editable: {
                type: 'select',
                pk: 1,
                source: [
                    {value: 1, text: '男'},
                    {value: 2, text: '女'},
                ]
            }
        },  {
            field: 'time',
            title: '时间',
            editable: {
                type: 'date',
                format: 'yyyy-mm-dd',    
                viewformat: 'yyyy-mm-dd',    
                datepicker: {
                    weekStart: 1
                }
            } 
        }]
    });

结果图如下:

bootstraptable实现x-editable的行单元格编辑及解决数据Empty和支持多样式

由于开源,很快就找到原因,由于formatter我们没有写这个function导致调用的默认的fZ喎?http://www.weiyer.com/Search.asp?KeyWord=/kf/ware/vc/" target="_blank" class="keylink">vcm1hdHRlcqOsxKzIz7XEw7vT0LDRse248bXE1rW0q8jraHRtbNbQo6xib290c3RyYXAtdGFibGUtZWRpdGFibGUuanPUtMLryOfPwiyz9cq8tqjS5V9kb250X2VkaXRfZm9ybWF0dGVyzqpmYWxzZaOsztLDx8O709DKtc/Wbm9lZGl0Rm9ybWF0dGVytcRmdW5jdGlvbr7Nu+HWtNDQtdq2/rj2aWbT777ko6zG5NbQtcSx6sep1tDDu9PQttTE2sjduLPWtaOstbzWwtfuuvPP1Mq+veG5+86qy/zErMjPtcRFbXB0eaO6PC9wPg0KPHByZSBjbGFzcz0="brush:sql;"> column.formatter = function(value, row, index) { var result = column._formatter ? column._formatter(value, row, index) : value; $.each(column, processDataOptions); $.each(editableOptions, function(key, value) { editableDataMarkup.push(' ' + key + '="' + value + '"'); }); var _dont_edit_formatter = false; if (column.editable.hasOwnProperty('noeditFormatter')) { _dont_edit_formatter = column.editable.noeditFormatter(value, row, index); } if (_dont_edit_formatter === false) { return ['' + '' ].join(''); } else { return _dont_edit_formatter; } };

由于要实现多样式,则把上面的代码改变,并在使用的时候实现noeditFormatter:function(value){…}就是了。将上面的代码改为如下(此为我自己改的,你可以根据自己的需要做修改):

column.formatter = function(value, row, index) {
                var result = column._formatter ? column._formatter(value, row, index) : value;

                $.each(column, processDataOptions);

                $.each(editableOptions, function(key, value) {
                    editableDataMarkup.push(' ' + key + '="' + value + '"');
                });

                var _dont_edit_formatter = false;
                if (column.editable.hasOwnProperty('noeditFormatter')) {
                    var process = column.editable.noeditFormatter(value, row, index);
                    if(!process.hasOwnProperty('class')){
                        process.class = '';
                    }
                    if(!process.hasOwnProperty('style')){
                        process.style = '';
                    }
                    _dont_edit_formatter = ['' + process.value + ''
                    ].join('');
                }

                if (_dont_edit_formatter === false) {
                    return ['' + value + ''
                    ].join('');
                } else {
                    return _dont_edit_formatter;
                }

            };

结果如下:

bootstraptable实现x-editable的行单元格编辑及解决数据Empty和支持多样式

bootstraptable实现x-editable的行单元格编辑及解决数据Empty和支持多样式

然后是bootstrap table的使用js文件,在其中实现noeditFormatter函数。返回的result必须包含filed和value,class和style可以不需要,class可以额外用其它插件之类,比如badge,style是增加样式(背景,颜色,字体等)。

$('#db_dependences').bootstrapTable({
        method:'POST',
        dataType:'json',
        contentType: "application/x-www-form-urlencoded",
        cache: false,
        striped: true,                              //是否显示行间隔色
        sidePagination: "client",           //分页方式:client客户端分页,server服务端分页(*)
        showColumns:true,
        pagination:true,
        minimumCountColumns:2,
        pageNumber:1,                       //初始化加载第一页,默认第一页
        pageSize: 10,                       //每页的记录行数(*)
        pageList: [10, 15, 20, 25],        //可供选择的每页的行数(*)
        uniqueId: "id",                     //每一行的唯一标识,一般为主键列
        showExport: true,                    
        exportDataType: 'all',
        exportTypes:[ 'csv', 'txt', 'sql', 'doc', 'excel', 'xlsx', 'pdf'],  //导出文件类型
        onEditableSave: function (field, row, oldValue, $el) {
            $.ajax({
                success: function (data, status) {
                    if (status == "success") {
                        alert("编辑成功");
                    }
                },
                error: function () {
                    alert("Error");
                },
                complete: function () {

                }
            });
        },
//      onEditableHidden: function(field, row, $el, reason) { // 当编辑状态被隐藏时触发
//          if(reason === 'save') {
//              var $td = $el.closest('tr').children();
//          //    $td.eq(-1).html((row.price*row.number).toFixed(2));
//          //    $el.closest('tr').next().find('.editable').editable('show'); //编辑状态向下一行移动
//          } else if(reason === 'nochange') {
//              $el.closest('tr').next().find('.editable').editable('show');
//          }
//      },
        data: [{
            id: 1,
            name: '张三',
            sex: '男',
            time: '2017-08-09'
        }, {
            id: 2,
            name: '王五',
            sex: '女',
            time: '2017-08-09'
        }, {
            id: 3,
            name: '李四',
            sex: '男',
            time: '2017-08-09'
        }, {
            id: 4,
            name: '杨朝来',
            sex: '男',
            time: '2017-08-09'
        }, {
            id: 5,
            name: '蒋平',
            sex: '男',
            time: '2017-08-09'
        }, {
            id: 6,
            name: '唐灿华',
            sex: '男',
            time: '2017-08-09'
        }, {
            id: 7,
            name: '马达',
            sex: '男',
            time: '2017-08-09'
        }, {
            id: 8,
            name: '赵小雪',
            sex: '女',
            time: '2017-08-09'
        }, {
            id: 9,
            name: '薛文泉',
            sex: '男',
            time: '2017-08-09'
        }, {
            id: 10,
            name: '丁建',
            sex: '男',
            time: '2017-08-09'
        }, {
            id: 11,
            name: '王丽',
            sex: '女',
            time: '2017-08-09'
        }],
        columns: [{
            field: 'id',
            title: '序号'
        }, {
            field: 'name',
            title: '姓名',
            editable: {
                type: 'text',  
                validate: function (value) {  
                    if ($.trim(value) == '') {  
                        return '姓名不能为空!';  
                    }  
                }
            } 
        }, {
            field: 'sex',
            title: '性别',
            editable: {
                type: 'select',
                pk: 1,
                source: [
                    {value: 1, text: '男'},
                    {value: 2, text: '女'},
                ],
                noeditFormatter: function (value,row,index) {
                    var result={filed:"sex",value:value,class:"badge",style:"background:#333;padding:5px 10px;"};
                    return result;
                }
            }
        },  {
            field: 'time',
            title: '时间',
            editable: {
                type: 'date',
                format: 'yyyy-mm-dd',    
                viewformat: 'yyyy-mm-dd',    
                datepicker: {
                    weekStart: 1
                },
                noeditFormatter: function (value,row,index) {
                    var result={filed:"time",value:value,class:"badge",style:"background:#333;padding:5px 10px;"};
                    return result;
                }
            } 
        }]
    });

关于bootstrap table的导出及使用可以看我另外一篇博客。

下载和引用

下载x-editable,并如下引用。



<script src="js/bootstrap_above/x-editable-develop/dist/bootstrap-editable/js/bootstrap-editable.js"></script><script src="js/bootstrap_above/bootstrap-table-develop/dist/extensions/editable/bootstrap-table-editable.js"></script>

然后讲上诉的一些文件修改添加,就完成了。

另外项目的结果展示

bootstraptable实现x-editable的行单元格编辑及解决数据Empty和支持多样式

bootstraptable实现x-editable的行单元格编辑及解决数据Empty和支持多样式

其中的样式都是自行在x-editable的基础上添加的。

Tags:BO OO OT TS 
作者:网络 来源:youand_me的