表格隔行換色(斑馬紋)與行選中高亮是後台管理系統的基礎交互。本文展示如何用 jQuery toggleClass() 以極簡代碼實現:Hover 高亮、Checkbox 選中切換、狀態持久化,代碼量較傳統 addClass/removeClass 減少 60%+。
<table id="table" width="50%" border="0" cellpadding="3" cellspacing="1">
<tr>
<td width="30" align="center"><input type="checkbox" class="check1" value="checkbox" /></td>
<td>腳本之家</td>
<td>腳本之家</td>
</tr>
<!-- 更多行... -->
</table>
.h { background: #f3f3f3; color: #000; } /* Hover 高亮 */
.c { background: #ebebeb; color: #000; } /* 選中狀態 */
$(function() {
// Hover 效果
$("#table tr").hover(function() {
$(this).addClass("h");
}, function() {
$(this).removeClass("h");
});
// Checkbox 選中切換
$("input").click(function() {
if ($(this).attr("checked")) {
$(this).closest("tr").addClass("c");
} else {
$(this).closest("tr").removeClass("c");
}
});
});
$(function() {
// Hover 切換:進入添加,離開移除
$("#table tr").hover(function() {
$(this).toggleClass("h");
});
// Checkbox 狀態同步:第二個參數決定強制添加/移除
$("input").click(function() {
var $tr = $(this).closest('tr');
// this.checked 為 true 時添加 .c,false 時移除 .c
$tr.toggleClass("c", this.checked);
});
});
// 基礎:切換類名(有則刪,無則加)
$(selector).toggleClass(className);
// 進階:根據布爾值強制控制
$(selector).toggleClass(className, state);
// state === true → 強制添加
// state === false → 強制移除
// 多類名:空格分隔或數組
$(selector).toggleClass("class1 class2");
$(selector).toggleClass(["class1", "class2"]);
| 場景 | 傳統寫法 | toggleClass |
|---|---|---|
| Hover | hover(add, remove) 兩個函數 | hover(toggle) 一個函數 |
| Checkbox 聯動 | if/else 判斷 checked | toggleClass(class, checked) |
| 代碼行數 | 12 行 | 6 行 |
| 邏輯耦合 | 高(手動管理狀態) | 低(聲明式) |
// 表頭全選 checkbox
$('#checkAll').click(function() {
var checked = this.checked;
$('.check1').prop('checked', checked) // 統一屬性
.closest('tr').toggleClass('c', checked); // 同步樣式
});
// 子選項變化時更新全選狀態
$('.check1').click(function() {
var allChecked = $('.check1:checked').length === $('.check1').length;
$('#checkAll').prop('checked', allChecked);
});
/* 純 CSS 隔行換色,性能最優、無閃爍 */
#table tr:nth-child(odd) { background: #f3f3f3; }
#table tr:nth-child(even) { background: #ebebeb; }
/* Hover 高亮優先級需高於斑馬紋 */
#table tr:hover { background: #f3f3f3 !important; }
/* 選中狀態(需 JS 切換 .selected 類) */
#table tr.selected { background: #d0e9f6 !important; }
建議:現代項目優先用 CSS :nth-child 做隔行換色,JS 僅處理「選中」等互動狀態。
toggleClass(className, state) 的布爾值控制特性,完美契合 Checkbox/Radio 等布爾狀態同步場景,讓 DOM 狀態管理變得聲明式、極簡、不易出錯。