<style>
.table-striped tbody tr:nth-child(odd) { background-color: #f9f9f9; }
.table-striped tbody tr:nth-child(even) { background-color: #fff; }
.table-striped tbody tr:hover { background-color: #eef7ff !important; }
</style>
<table class="table-striped">
<thead><tr><th>姓名</th><th>年齡</th></tr></thead>
<tbody>
<tr><td>張三</td><td>25</td></tr>
<tr><td>李四</td><td>30</td></tr>
</tbody>
</table>
若表格內容由 AJAX 動態載入,需在渲染後重新套用:
function applyTableStriping($table) {
$table.find("tbody tr").removeClass("odd even") // 清除舊類
.filter(":odd").addClass("odd").end() // 奇數行(索引 1,3... 即第 2,4 行)
.filter(":even").addClass("even"); // 偶數行(索引 0,2... 即第 1,3 行)
// 懸停高亮(事件委派,支援動態新增行)
$table.off("mouseenter mouseleave", "tbody tr")
.on("mouseenter", "tbody tr", function() {
$(this).addClass("hover");
})
.on("mouseleave", "tbody tr", function() {
$(this).removeClass("hover");
});
}
// CSS 配合
// .table-striped tbody tr.odd { background: #f9f9f9; }
// .table-striped tbody tr.even { background: #fff; }
// .table-striped tbody tr.hover { background: #eef7ff !important; }
// 使用:AJAX 成功後呼叫
$.get("/api/data", html => {
$("#dataTable tbody").html(html);
applyTableStriping($("#dataTable"));
});
function stripeTable(table) {
const rows = table.querySelectorAll("tbody tr");
rows.forEach((row, i) => {
row.classList.toggle("odd", i % 2 === 1);
row.classList.toggle("even", i % 2 === 0);
});
// 懸停用 CSS :hover 即可,無需 JS
}
// 動態新增行後重新套用
function addRow(table, data) {
const tbody = table.tBodies[0];
const row = tbody.insertRow();
data.forEach(text => row.insertCell().textContent = text);
stripeTable(table); // 重新計算奇偶
}
| 方案 | 效能 | 維護性 | 動態內容支援 |
|---|---|---|---|
| CSS nth-child | ⭐⭐⭐⭐⭐ (瀏覽器原生) | ⭐⭐⭐⭐⭐ | 自動生效 |
| jQuery 類切換 | ⭐⭐⭐ (需遍歷 DOM) | ⭐⭐⭐ | 需手動觸發 |
| 原生 JS 類切換 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | 需手動觸發 |
結論: 靜態表格**只用 CSS**;動態表格採用**原生 JS + CSS :hover**,僅在極舊專案維護時用 jQuery。