bootstrap-table 表格行内编辑实现

bootstrap-table 表格行内编辑实现

这篇文章向大家介绍一下如何使用bootstrap table插件实现表格的行内编辑功能。

推荐教程:Bootstrap框架

先放一张效果图:

bootstrap-table 表格行内编辑实现

应用场景 

之前的项目也是采用bootstrap table,添加和修改数据都是通过模态框来编辑的,后来有了点击行来编辑和新增的需求,于是乎试试…… 

html

  1.     
                        
        

登录后复制

script

  1. $(function() {    let $table = $('#table');    let $button = $('#button');    let $getTableData = $('#getTableData');    $button.click(function() {        $table.bootstrapTable('insertRow', {            index: 0,            row: {                id: '',                name: '',                price: ''            }        });    });    $table.bootstrapTable({        url: 'data2.json',        toolbar: '#toolbar',        clickEdit: true,        showToggle: true,        pagination: true,       //显示分页条        showColumns: true,        showPaginationSwitch: true,     //显示切换分页按钮        showRefresh: true,      //显示刷新按钮        //clickToSelect: true,  //点击row选中radio或CheckBox        columns: [{            checkbox: true        }, {            field: 'id',            title: 'Item ID'        }, {            field: 'name',            title: 'Item Name'        }, {            field: 'price',            title: 'Item Price'        }, ],        /**         * @param {点击列的 field 名称} field         * @param {点击列的 value 值} value         * @param {点击列的整行数据} row         * @param {td 元素} $element         */        onClickCell: function(field, value, row, $element) {            $element.attr('contenteditable', true);            $element.blur(function() {                let index = $element.parent().data('index');                let tdValue = $element.html();                saveData(index, field, tdValue);            })        }    });    $getTableData.click(function() {        alert(JSON.stringify($table.bootstrapTable('getData')));    });    function saveData(index, field, value) {        $table.bootstrapTable('updateCell', {            index: index,       //行索引            field: field,       //列名            value: value        //cell值        })    }});

登录后复制

实现原理 

通过bootstrap table自带的 onClickCell 方法,点击 td 添加 contenteditable 属性(ps: 使元素可编辑),于是 td 元素具有了类似于文本框的 focus 和 blur 事件,用户点击 td 获取焦点,编辑完内容失去焦点后,调用 updateCell方法更新单元格数据。 

引入

  1.                      

登录后复制

json

  1. [    { "id": 1, "name": "Item 1", "price": "¥1" },    { "id": 2, "name": "Item 2", "price": "¥2" },    { "id": 3, "name": "Item 3", "price": "¥3" }]

登录后复制

以上就是bootstrap-table 表格行内编辑实现的详细内容,更多请关注【创想鸟】其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

点点赞赏,手留余香

给TA打赏
共0人
还没有人赞赏,快来当第一个赞赏的人吧!
    编程技术

    Bootstrap分页表格插件使用教程

    2025-3-30 6:56:14

    编程技术

    bootstrap table轻松实现数据表格

    2025-3-30 6:56:23

    0 条回复 A文章作者 M管理员
    欢迎您,新朋友,感谢参与互动!
      暂无讨论,说说你的看法吧
    个人中心
    购物车
    优惠劵
    今日签到
    私信列表
    搜索