解決bootstrap table行拖拽與獲取數據的問題后,又來一個新問題
在此將解決方案分享出來。
前提準備
bootstrap table 好用的多功能表格 中文官網 github
bootstrap-table-reorder-rows 上述表格的一個擴展,支持行拖拽 github
問題
以上為原表格,已設置uniqueid=id,拖動行更換位置后如下圖
在刪除按鈕點擊事件中獲取行的id號,并用removeByUniqueId方法刪除當前行,發現刪除的并不是當前行,原因是拖拽排序后,row.id發生了改變,不再與uniqueid相同。但是uniqueid不屬于表格的字段,不能在row對象中獲取。
解決方法
再用removeByUniqueId方法刪除當前行
var uid=$(this).parent().parent().attr("data-uniqueid");
$('#tabletest').bootstrapTable('removeByUniqueId', uid);
完整的html源碼如下,可直接另存為html后進行測試
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet">
<link rel="stylesheet">
<link rel="stylesheet">
</head>
<body>
<div style="width:1000px">
<table id="tabletest" data-unique-id="idx">
</table>
</div>
<div id="toolbar" class="btn-group">
<button id="btn_add" type="button" class="btn btn-info btn-sm rightSize">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
</button>
</div>
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-table/1.12.2/bootstrap-table.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-table/1.12.2/locale/bootstrap-table-zh-CN.js"></script>
<script src="https://cdn.bootcss.com/TableDnD/1.0.3/jquery.tablednd.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-table/1.12.2/extensions/reorder-rows/bootstrap-table-reorder-rows.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#tabletest").bootstrapTable({
reorderableRows: true,
striped: true,
search: true,
toolbar: '#toolbar',
useRowAttrFunc: true,
columns: [{
field: 'idx',
title: '編號'
}, {
field: 'name',
title: '名稱'
}, {
field: 'price',
title: '價格'
}, {
field: 'button',
title: '操作',
events: operateEvents,
formatter: operateFormatter
}],
data: [{
idx: 1,
name: 'Item 1',
price: '$1'
}, {
idx: 2,
name: 'Item 2',
price: '$2'
}]
});
});
$("#btn_add").click(function () {
var rowCount = $('#tabletest').bootstrapTable('getData').length;
$('#tabletest').bootstrapTable('append', { 'idx': rowCount + 1, 'name': 'bb', 'price': rowCount + 1 });
})
function operateFormatter(value, row, index) {
return [
'<button type="button" class="btn btn-default" id="rowDel">刪除</button>'
].join('');
};
window.operateEvents = {
'click #rowDel': function (e, value, row, index) {
var uid=$(this).parent().parent().attr("data-uniqueid");
$('#tabletest').bootstrapTable('removeByUniqueId', uid);
}
};
</script>
</body>
</html>