選項卡是最基礎的 UI 組件之一。對比原生 JS 與 jQuery 兩種實現方式,不僅能理解 DOM 操作與庫封裝的差異,更能啟發組件化設計思維。本文提供兩套功能等效、樣式復用的完整代碼,並從 API 設計、性能、維護性等維度深度對比。
<style>
.tab { margin: 10px auto; width: 300px; position: relative; font: 13px/20px SimSun, Arial; }
.tabTitle ul { overflow: hidden; } .tabTitle li { float: left; padding: 7px 15px; border: 1px solid #ddd; margin-right: -1px; background: linear-gradient(#fefefe, #ededed); cursor: pointer; }
.tabTitle li.active { background: #fff; font-weight: bold; }
.tabContent { border: 1px solid #eee; height: 100px; position: relative; }
.tabContent > div { position: absolute; top: 0; left: 0; width: 100%; padding: 5px; opacity: 0; display: none; }
.tabContent > div.current { opacity: 1; display: block; }
</style>
<div id="tab" class="tab">
<div class="tabTitle">
<ul><li class="active">標題一</li><li>標題二</li><li>標題三</li><li>標題四</li></ul>
</div>
<div class="tabContent">
<div class="current">內容一 aaaaaaaaa</div>
<div>內容二 bbbbbbbbb</div>
<div>內容三 ccccccccc</div>
<div>內容四 ddddddddd</div>
</div>
</div>
<script>
(function() {
var tab = document.getElementById("tab");
var tabs = tab.querySelectorAll(".tabTitle li");
var panels = tab.querySelectorAll(".tabContent > div");
// 綁定點擊事件
tabs.forEach(function(tabEl, index) {
tabEl.index = index; // 掛載索引
tabEl.onclick = function() { switchTab(this.index); };
});
function switchTab(index) {
tabs.forEach(function(el, i) {
el.className = i === index ? "active" : "";
panels[i].className = i === index ? "current" : "";
});
}
})();
</script>
<script src="jquery.min.js"></script>
<script>
$(function() {
var $tabs = $(".tabTitle li");
var $panels = $(".tabContent > div");
$tabs.click(function() {
var idx = $tabs.index(this); // 獲取索引
$tabs.removeClass("active").eq(idx).addClass("active");
$panels.removeClass("current").eq(idx).addClass("current");
});
});
</script>
| 維度 | 原生 JS | jQuery |
|---|---|---|
| 代碼量 | 稍多(需手寫迭代、綁定) | 極少(隱式迭代、鏈式) |
| 性能 | 最優(直接 DOM API,無封裝開銷) | 微弱開銷(選擇器解析、對象包裹),現代瀏覽器可忽略 |
| 兼容性 | 需自處理 IE 兼容(classList、addEventListener) | 庫內部已統一處理 |
| 可讀性 | 語義顯式,適合教學理解本質 | DSL 風格,業務邏輯更聚焦 |
| 擴展性 | 需手寫插件機制 | 天然支持 $.fn.tab = ... 插件化 |
| 依賴體積 | 0 KB | ~30 KB (jQuery 3.x min+gz) |
class TabComponent {
constructor(root) {
this.$root = $(root);
this.$tabs = this.$root.find(".tabTitle li");
this.$panels = this.$root.find(".tabContent > div");
this.bind();
}
bind() {
this.$tabs.on("click", (e) => this.switch($(e.currentTarget).index()));
}
switch(index) {
this.$tabs.removeClass("active").eq(index).addClass("active");
this.$panels.removeClass("current").eq(index).addClass("current");
this.$root.trigger("tab:change", [index]); // 事件總線,解耦業務
}
}
// 實例化
$(".tab").each(function() { new TabComponent(this); });
這種寫法:
✅ 狀態封裝、可多實例共存
✅ 事件驅動解耦業務邏輯
✅ 易於單元測試、TypeScript 類型標註
✅ 可平遷至 Vue/React 組件(props/emit 對應)
Tab 組件看似簡單,實則蘊含「狀態管理、事件綁定、DOM 更新、插件化、框架遷移」完整知識鏈。通過對比兩種寫法,能清晰看到庫/框架解決的核心痛點,為技術選型提供理性依據。