data数据为json文件 data2.json
[
{ "id": 1, "name": "Item 1", "price": "¥1" },
{ "id": 2, "name": "Item 2", "price": "¥2" },
{ "id": 3, "name": "Item 3", "price": "¥3" }
]
html文件
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<body class="gray-bg">
<link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.15.3/dist/bootstrap-table.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://unpkg.com/bootstrap-table@1.15.3/dist/bootstrap-table.min.js" type="text/javascript" charset="utf-8"></script>
<script src="https://unpkg.com/bootstrap-table@1.15.3/dist/locale/bootstrap-table-zh-CN.min.js"></script>
<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>
</body>
<script type="text/javascript">
$(function() {
var data2 = [
{ "id": 1, "name": "Item 1", "price": "¥1" },
{ "id": 2, "name": "Item 2", "price": "¥2" },
{ "id": 3, "name": "Item 3", "price": "¥3" }
];
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',
dataType: 'jsonp',
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值
})
}
});
</script>
</html>