bootstrap table行编辑

关于bootstrap table自带的行编辑解决方案可以参考以下文章

https://www.cnblogs.com/landeanfen/p/5821192.html

以下文章是另外一种功能解决方案,但是下载链接已经失效,因此我只有自己想想办法了

http://blog.csdn.net/lzxadsl/article/details/49181127

模仿的是失效的那种,好了,开始

首先,利用H5的contenteditable 将内容设为可编辑的

{
    title: '评分',
    width: '100px',
    field: 'score',
    formatter:function (value, row, index, field) {
        return '<div contenteditable="true">' + (value || "-") + '</div>';
    }

}
其次利用jquery添加可编辑属性的全局change事件

//contenteditable绑定change事件
$('body').on('focus', '[contenteditable]', function() {
    var $this = $(this);
    $this.data('before', $this.html());
    return $this;
}).on('blur keyup paste input', '[contenteditable]', function() {
    var $this = $(this);
    if ($this.data('before') !== $this.html()) {
        $this.data('before', $this.html());
        $this.trigger('change');
    }
    return $this;
});
参考:https://stackoverflow.com/questions/1391278/contenteditable-change-events

然后为需要修改的列绑定内容change事件,

关键是获取到BootstapTable对象,此对象放在表格jquery对象的data("bootstrap.table")中

获取到此对象之后就可对表格的数据做操作了

function bind_edit_score_blur(field) {
    var $table = $("#work_table");
    //bootstrap table对象,包含了所有表格的内容,data中存储了加载过来的当前页数据
    var data = $table.data("bootstrap.table").data;
    var col = $table.find("thead tr th[data-field=" + field + "]").index();
    //因为每次加载table都会删除所以事件不会重复绑定
    $table.find("tbody tr").find('td:eq('+col+') div').on('change',function () {
        var value = $(this).text();
        var row = $(this).parents('tr').data('index');
        console.log(value);
        //修改表格对象的数据
        data[row][field]=value;
        $table.bootstrapTable('check', row);
    });
}
此事件的绑定,我是放在了onpostbody中,并且写了个循环,因为我不知道bootstrap table初始化完毕的回调,

onPostBody:function () {
    //绑定评分修改事件,因为不知道table什么时候初始化完毕
    var check_table_finished=setInterval(function () {
        var bootstrapTable = $("#work_table").data("bootstrap.table");
        if(bootstrapTable) {
            clearInterval(check_table_finished);
            //绑定评分修改后的事件
            bind_edit_score_blur('score');
        }
    },500);
},
最后提交修改的内容就可以了

function updateScore() {
    var row = $('#work_table').bootstrapTable('getSelections');
    if(row.length == 0) {
        toastr.success("请先选中一条评分");
        return;
    }    
    $.each(row,function (i, item) {
        var workid = item.workid;
        var score = item.score;
        $.ajax({
            url:ROOT_URL+'commonAction/updateScore',
            type:"post",
            dataType:"json",
            data:{
                workid:workid,
                score:score
            },
            success:function(res){
                if(res.status == 0) {
                    toastr.success(res.msg);
                }else{
                    toastr.error(res.msg);
                }
                query();
            }
        });
    });


}
表格效果: