常見的 Tab 選單或樣本選擇器需求:點擊某項目時,該項目高亮(加上 active 樣式),其餘同輩元素移除高亮。本文提供純 jQuery + CSS 的極簡實現,適合模板選擇、分頁標籤等場景。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>jQuery 同輩元素選中/未選中效果</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.templink, .templinkactive {
display: block;
padding: 5px;
cursor: pointer;
text-decoration: none;
}
.templinkactive {
background-color: #2788DA;
color: #ffffff;
}
</style>
<script>
$(function() {
// 使用事件委派,支援動態新增
$("#linktable").on("click", "span", function() {
// 移除所有同輩的 active 樣式
$(this).addClass("templinkactive")
.siblings("span") // 若同層級
.removeClass("templinkactive")
.addClass("templink");
// 若結構為 table > tr > td > span,改用:
// $(this).closest("table").find("span").removeClass("templinkactive").addClass("templink");
// $(this).removeClass("templink").addClass("templinkactive");
});
});
</script>
</head>
<body>
<table id="linktable" width="100%">
<tr><td><span class="templink" data-id="001">模板001 (一行三列)</span></td></tr>
<tr><td><span class="templink" data-id="002">模板002 (一行四列)</span></td></tr>
<tr><td><span class="templink" data-id="003">模板003 (一行三列)</span></td></tr>
<tr><td><span class="templink" data-id="004">模板004 (一行四列)</span></td></tr>
<tr><td><span class="templink" data-id="005">模板005 (一行三列)</span></td></tr>
</table>
</body>
</html>
.on() 事件委派,綁定在父容器 #linktable,效能佳且支援動態新增。.siblings() 僅針對同層級元素;若結構較深,改用 .closest("table").find("span") 選取所有候選項。data-id 屬性儲存識別碼,避免使用 id 字串拼接。$("#linktable").on("click", "span", function() {
const selectedId = $(this).data("id");
console.log("選中模板:", selectedId);
// 後續邏輯:AJAX 載入模板、更新預覽等
});
document.getElementById("linktable").addEventListener("click", e => {
if (e.target.matches("span")) {
document.querySelectorAll("#linktable span").forEach(s => s.classList.remove("templinkactive"));
e.target.classList.add("templinkactive");
}
});