这篇文章向大家介绍一下如何使用bootstrap table插件实现表格的行内编辑功能。
推荐教程:bootstrap框架
先放一张效果图:
应用场景
之前的项目也是采用bootstrap table,添加和修改数据都是通过模态框来编辑的,后来有了点击行来编辑和新增的需求,于是乎试试……
html
<div class="table-box" style="margin: 20px;"> <div id="toolbar"> <button id="button" class="btn btn-default">insertrow</button> <button id="gettabledata" class="btn btn-default">gettabledata</button> </div> <table id="table"></table></div>
script
$(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方法更新单元格数据。
引入
<link rel="stylesheet" type="text/css" href="js/bootstrap/bootstrap-3.3.7-dist/css/bootstrap.min.css" /> <link rel="stylesheet" type="text/css" href="js/bootstrap-table/1.12.1/bootstrap-table.min.css" /> <script src="js/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script src="js/bootstrap/bootstrap-3.3.7-dist/js/bootstrap.min.js" type="text/javascript" charset="utf-8"></script> <script src="js/bootstrap-table/1.12.1/bootstrap-table.min.js" type="text/javascript" charset="utf-8"></script> <script src="js/bootstrap-table/1.12.1/locale/bootstrap-table-zh-cn.min.js" type="text/javascript" charset="utf-8"></script>
json
[ { "id": 1, "name": "item 1", "price": "¥1" }, { "id": 2, "name": "item 2", "price": "¥2" }, { "id": 3, "name": "item 3", "price": "¥3" }]
以上就是bootstrap-table 表格行内编辑实现的详细内容。