Bootstrap Table 是一個基於 Bootstrap 的輕量級表格插件。它的賣點是「設定少、功能多」——固定表頭、單複選、排序、分頁、搜尋、自訂表頭這些常見需求,幾乎都只要給對參數就能拿到。
最小組合是這五個:
順序要注意:jQuery 必須在 bootstrap.js 之前,而 bootstrap-table.js 又要在兩者之後。
在 table 標籤上設定 data-toggle="table",就能在不寫任何 JS 的情況下啟用 Bootstrap Table:
<table data-toggle="table" data-url="data.json">
<thead>
...
</thead>
</table>
這種宣告式寫法很適合簡單場景,缺點是設定一多,HTML 上會堆滿 data-* 屬性,可讀性反而變差。
<table id="table"></table>
<!-- 1. 簡單的靜態資料 -->
<script>
$('#table').bootstrapTable({
columns: [
{ field: 'id', title: 'Item ID' },
{ field: 'username', title: 'Item Username' },
{ field: 'password', title: 'Item Passowrd' }
],
data: [
{ id: 1, username: 'Item 1', passowrd: '$1' },
{ id: 2, username: 'Item 2', password: '$2' }
]
});
</script>
<!-- 2. 透過 url 取得資料 -->
<script>
$('#table').bootstrapTable({
url: 'data1.json',
columns: [
{ field: 'id', title: 'Item ID' },
{ field: 'username', title: 'Item Username' },
{ field: 'passowrd', title: 'Item Passowrd' }
]
});
</script>
命令式寫法的優勢在於可以動態更新。例如要重新載入資料、切換頁碼、或依搜尋條件刷新,都能透過 $('#table').bootstrapTable('refresh', {...}) 這類呼叫完成。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Bootstrap Table 的 demo</title>
<link rel="stylesheet" href="bootstrap.css">
<link rel="stylesheet" href="bootstrap-table.css">
</head>
<body>
<table id="table"></table>
<!--引入相關的 js 檔案-->
<script src="jquery.min.js"></script>
<script src="bootstrap.js"></script>
<script src="bootstrap-table.js"></script>
<!--自定義 javaScript-->
<script>
$('#table').bootstrapTable({
columns: [
{ field: 'id', title: 'Item ID' },
{ field: 'username', title: 'Item Username' },
{ field: 'passsword',title: 'Item Password' }
],
data: [
{ id: 1, username: 'Item 1', passowrd: '123' },
{ id: 2, username: 'Item 2', passowrd: '123' }
]
});
</script>
</body>
</html>
上面兩段程式碼裡,columns 定義的 field 名稱與 data 中的實際鍵名並不一致——columns 寫 passsword(三個 s),data 寫 passowrd(字母順序錯置),兩者都不是正確的 password。
後果是那一欄會顯示為空白。這其實反映了一個實作上的現實:field 名稱必須與資料物件的鍵名完全一致,拼錯一個字母不會報錯,只會安靜地顯示空值。資料量大時這種問題不好察覺,建議在開發階段先確認欄位對應無誤。
pagination: true 搭配 pageSize、pageListsearch: truesortable: truesingleSelect 或欄位的 checkbox: trueheight 後表頭會自動固定這些選項彼此獨立,可以任意組合。實務上最常見的組合是「遠端分頁 + 服務端排序 + 複選」,此時要記得在 columns 中把 searchable、orderable 等行為與後端 API 對齊,否則前端排序只會作用於當前頁的資料。