function stripeTables() {
if (!document.getElementsByTagName) return;
var tables = document.getElementsByTagName("table");
for (var i = 0; i < tables.length; i++) {
var rows = tables[i].getElementsByTagName("tr");
for (var j = 0; j < rows.length; j++) {
if (j % 2 === 0) {
rows[j].style.backgroundColor = "#f9f9f9"; // 奇數行 (0-index)
} else {
rows[j].style.backgroundColor = "#fff";
}
}
}
}
window.onload = stripeTables;
:nth-child 難以覆蓋 (需 !important):nth-child/* CSS 檔案 */
#data-table tbody tr:nth-child(odd) { background:#f9f9f9; }
#data-table tbody tr:nth-child(even) { background:#fff; }
<!--[if lte IE 8]>
<script>
// 僅 IE8 執行
function stripeIE8() { ... }
window.onload = stripeIE8;
</script>
<![endif]-->
<tr data-row-index="0">...</tr>
<tr data-row-index="1">...</tr>
/* CSS */
tr[data-row-index] { --row: attr(data-row-index); } /* 無法直接用 attr 於數學運算 */
實務上:Vue/React 直接在渲染時綁定 :class="{odd: index%2===0}",或用 CSS :nth-child 完全脫離 JS。
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>表格斑馬紋</title>
<style>
table { border-collapse:collapse; width:100%; }
th, td { border:1px solid #ddd; padding:.5rem; }
tbody tr:nth-child(odd) { background:#f5f5f5; }
tbody tr:hover { background:#e3f2fd; } /* 滑鼠懸停高亮優先 */
</style></head><body>
<table id="data-table">
<thead><tr><th>姓名</th><th>城市</th></tr></thead>
<tbody>
<tr><td>張三</td><td>台北</td></tr>
<tr><td>李四</td><td>台中</td></tr>
<tr><td>王五</td><td>高雄</td></tr>
</tbody>
</table>
</body></html>
**現代專案請直接用 CSS :nth-child**,只有維護極舊 IE8 專案才需 JS 兜底,並以條件編譯隔離。將樣式邏輯留在 CSS、行為邏輯留在 JS,關注點分離、可維護性最高。