需求:ASP 網頁顯示銷售匯總資料,點擊匯總列展開/收合對應明細列。
class="parent" 與唯一 id="row_01"。class="child_row_01"(對應父列 id)。click 事件,切換明細列顯示/隱藏並切換父列樣式。<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>明細展開收合示例</title>
<style>
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; font: 14px/1.5 "Microsoft JhengHei"; }
th { background: #333; color: #fff; }
.parent { background: #e8f4fd; cursor: pointer; font-weight: bold; }
.child_row_01, .child_row_02, .child_row_03 { display: none; background: #f9f9f9; }
.parent.selected { background: #d0e8f0; }
</style>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script>
$(function() {
$('tr.parent').click(function() {
$(this).toggleClass('selected')
.siblings('.child_' + this.id).toggle();
});
});
</script>
</head>
<body>
<table>
<thead><tr><th>區域</th><th>銷售額</th><th>目標</th></tr></thead>
<tbody>
<tr class="parent" id="row_01"><td>東南區</td><td>5001</td><td>71000</td></tr>
<tr class="child_row_01"><td>東南一分部</td><td>4000</td><td>50000</td></tr>
<tr class="child_row_01"><td>東南二分部</td><td>1000</td><td>10000</td></tr>
<tr class="parent" id="row_02"><td>西南區</td><td>1233</td><td>456555</td></tr>
<tr class="child_row_02"><td>西南一分部</td><td>1233</td><td>456555</td></tr>
</tbody>
</table>
</body>
</html>
Repeater 或 GridView 綁定巢狀資料,或手動拼接 HTML 字串輸出。id 唯一,明細列 class 對應 child_ + 父列id。此做法不需 PostBack,純前端操作,體驗流暢,適合大量資料的主從表展示。