前端開發:使用bootstrap-table.js來實現表格的排序

bootstrap-table.js 是一個以為bootstrap為基礎的表格外掛。可以對表格的資料進行排序、分頁、查詢等等。
本篇文章將簡單的介紹如果套用bootstrap-table.js到表格上,進行排序。
因為bootstrap-table.js是以bootstrap為基礎開發的套件,因為我們必須先載入bootstrap。另外bootstrap-table使用了font awesome作為預設的圖標,因此我們也需要找入font awesome。
匯入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">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/bootstrap-table.min.css">
匯入Javascript
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></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/[email protected]/dist/bootstrap-table.min.js"></script>
HTML
<table id="sort-table" data-toggle="table">
<thead>
<tr>
<th data-field="id" data-sortable="true">ID</th>
<th data-field="name" data-sortable="true">Item Name</th>
<th data-field="price" data-sortable="true">Item Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Orange</td>
<td>102</td>
</tr>
<tr>
<td>2</td>
<td>Guava</td>
<td>8</td>
</tr>
<tr>
<td>3</td>
<td>Grape</td>
<td>59</td>
</tr>
<tr>
<td>4</td>
<td>Apple</td>
<td>45</td>
</tr>
</tbody>
</table>
只要在<table>的標籤裡加上 data-toggle="table" 就可以直接套用bootstrap-table.js到表格上。
你也可以利用javascript 來套用 bootstrap-table.js
$('#sort-table').bootstrapTable();
如果要設定排序的功能,那麼就在需要排序的欄位的<th>裡加上 data-field="name" data-sortable="true", 不需要排序的欄位則是data-field="name" data-sortable="false"
還有更多進階的使用方法,你可以參考官網的範例: https://examples.bootstrap-table.com/
提供codepen 範例給您參考: https://codepen.io/ellen-shih/pen/mdedYBV
我要留言