利用索引對應:點擊標籤 <li> 取得索引,移除所有標籤 .current 類別並加到當前,同時隱藏所有內容面板 <ul> 只顯示對應索引面板。邏輯清晰、代碼極簡。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery 簡易選項卡</title>
<style>
* { margin:0; padding:0; }
body { font:12px/1.5 Tahoma; }
#outer { width:450px; margin:10px auto; }
#tab { overflow:hidden; zoom:1; background:#000; border:1px solid #000; }
#tab li { float:left; color:#fff; height:30px; cursor:pointer; line-height:30px; list-style:none; padding:0 20px; }
#tab li.current { color:#000; background:#ccc; }
#content { border:1px solid #000; border-top-width:0; }
#content ul { line-height:25px; display:none; margin:0 30px; padding:10px 0; }
</style>
</head>
<body>
<div id="outer">
<ul id="tab">
<li class="current">第一課</li>
<li>第二課</li>
<li>第三課</li>
</ul>
<div id="content">
<ul style="display:block;">1111</ul>
<ul>2222</ul>
<ul>3333</ul>
</div>
</div>
<script src="https://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
$(function() {
var $li = $('#tab li');
var $ul = $('#content ul');
$li.click(function() {
$li.removeClass();
var idx = $(this).index();
$(this).addClass('current');
$ul.css('display', 'none');
$ul.eq(idx).css('display', 'block');
});
});
</script>
</body>
</html>
$(this).index() 取得在同輩元素中的索引(從 0 開始)。$ul.eq(idx) 選取對應索引的面板。.current,第一個面板 style="display:block;"。.hover() 或鍵盤支援(左右鍵切換、Enter 啟用)。$ul.eq(idx).fadeIn().siblings().hide()。role="tablist"、aria-selected、aria-controls 等 ARIA 屬性。