表格互動三大經典需求:隔行變色(斑馬紋)、滑鼠懸停行高亮、按鈕切換資料源。本文提供完整原生 JS 實作,邏輯清晰、可直接套用,並附現代 CSS 與框架化改寫建議。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Table 隔行色、懸停高亮、動態切換資料</title>
<style>
/* 基礎樣式 */
#tblMain { border-collapse: collapse; width: 100%; }
#tblMain td { padding: 8px 12px; border: 1px solid #ddd; }
#tblMain tr:nth-child(even) { background: #f9f9f9; } /* CSS 隔行色,無需 JS */
#tblMain tr:hover { background: #e8f4fd !important; } /* CSS 懸停高亮,優先級最高 */
</style>
<script>
// 兩組測試資料
var data1 = {
"李莫": "畢業於清華大學",
"周平": "畢業於北京大學",
"羅達": "畢業於哈爾濱大學",
"鄭朵": "畢業於河南大學",
"王天": "畢業於湖南大學"
};
var data2 = {
"三聯": "https://www.3lian.net",
"搜狐網": "https://www.sohu.com",
"CSDN程式設計師開發網站": "https://www.csdn.net",
"百度": "https://www.baidu.com",
"網易": "https://www.163.com"
};
function toggleData() {
var btn = document.getElementById("btnToggle");
if (btn.value === "資料1") {
loadData(data1, "資料2");
} else {
loadData(data2, "資料1");
}
}
function loadData(dataSource, nextBtnLabel) {
var table = document.getElementById("tblMain");
// 清空現有資料列 (保留 thead 若有)
var tbody = table.tBodies[0] || table;
while (tbody.rows.length > 0) {
tbody.deleteRow(0);
}
// 填入新資料
var index = 0;
for (var key in dataSource) {
var row = tbody.insertRow(-1); // -1 附加到末尾
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.textContent = key;
cell2.textContent = dataSource[key];
// JS 隔行色 (若不信任 CSS nth-child)
// row.style.background = (index % 2 === 0) ? "yellow" : "white";
index++;
}
btn.value = nextBtnLabel;
}
// 初始化
window.onload = function() {
loadData(data1, "資料2");
};
</script>
</head>
<body>
<table id="tblMain">
<thead>
<tr><th>名稱</th><th>內容</th></tr>
</thead>
<tbody></tbody>
</table>
<input type="button" id="btnToggle" value="資料2" onclick="toggleData()" />
</body>
</html>
/* 取代 JS 迴圈設定 background */
tbody tr:nth-child(even) { background: #f2f2f2; }
tbody tr:nth-child(odd) { background: #fff; }
/* !important 覆蓋隔行色 */
tbody tr:hover { background: #e3f2fd !important; }
.table-row-selected { background: #fff3e0 !important; font-weight: bold; }
// JS
tbody.addEventListener('click', e => {
const row = e.target.closest('tr');
if (!row || row.parentElement.tagName === 'THEAD') return;
[...tbody.rows].forEach(r => r.classList.remove('table-row-selected'));
row.classList.add('table-row-selected');
});
const TableManager = {
table: document.getElementById('tblMain'),
datasets: {
users: { /* ... */ },
sites: { /* ... */ }
},
current: 'users',
init() {
this.render(this.current);
document.getElementById('btnToggle').addEventListener('click', () => this.switch());
},
render(key) {
const data = this.datasets[key];
const tbody = this.table.tBodies[0];
tbody.innerHTML = ''; // 現代瀏覽器安全
Object.entries(data).forEach(([k, v]) => {
const tr = tbody.insertRow();
tr.insertCell().textContent = k;
tr.insertCell().textContent = v;
});
this.current = key;
},
switch() {
this.render(this.current === 'users' ? 'sites' : 'users');
}
};
TableManager.init();
<!-- Vue 3 -->
<table>
<thead><tr><th>名稱</th><th>內容</th></tr></thead>
<tbody>
<tr v-for="(v, k) in currentData" :key="k" :class="{ selected: selectedKey === k }" @click="selectedKey = k">
<td>{{ k }}</td>
<td>{{ v }}</td>
</tr>
</tbody>
</table>
<button @click="toggleData">切換到 {{ nextLabel }}</button>
<script setup>
import { ref, computed } from 'vue';
const data1 = { ... }, data2 = { ... };
const currentData = ref(data1);
const nextLabel = ref('資料2');
const selectedKey = ref(null);
const toggleData = () => {
currentData.value = currentData.value === data1 ? data2 : data1;
nextLabel.value = currentData.value === data1 ? '資料2' : '資料1';
};
</script>
Table 互動三大件:隔行色交給 CSS nth-child、懸停高亮交給 CSS hover、資料渲染交給 JS、選中狀態交給 class 切換。關注點分離讓程式碼更簡潔、效能更好、維護更容易。