在 JSP 或任何服務端渲染的表格中,實現「點擊行高亮、單選/多選切換」應使用**事件委託**,避免為每行綁定 onclick、內聯 JS 混雜 Java 代碼。本文提供現代化、無依賴的實現方案。
<table> 上綁定**單個** click 監聽器。event.target 最近的 <tr>。selected 類名,樣式完全由 CSS 控制。<input type="checkbox"> 實現多選/單選邏輯。<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>搜索結果行高亮</title>
<style>
.result-table { border-collapse: collapse; width: 100%; font-size: 14px; }
.result-table th, .result-table td { border: 1px solid #e0e0e0; padding: 10px 12px; text-align: center; }
.result-table th { background: #f5f5f5; font-weight: 600; }
.result-table tbody tr { cursor: pointer; transition: background .15s; }
.result-table tbody tr:hover { background: #fafafa; }
/* 高亮類名 */
.result-table tbody tr.selected { background: #e3f2fd !important; }
.result-table input[type=checkbox] { transform: scale(1.1); cursor: pointer; }
</style>
</head>
<body>
<table class="result-table" id="resultTable">
<thead>
<tr>
<th style="width:40px"><input type="checkbox" id="checkAll"></th>
<th>資產編號</th>
<th>序列號</th>
<th>資產名稱</th>
<th>分類</th>
<th>採購日期</th>
<th>歸檔日期</th>
<th>配置信息</th>
</tr>
</thead>
<tbody>
<%
// 假設 List list = request.getAttribute("list");
for (Asset info : list) {
String rowId = "row_" + info.getId();
String chkId = "chk_" + info.getId();
%>
<tr id="<%=rowId%>" data-id="<%=info.getId()%>">
<td><input type="checkbox" class="row-check" id="<%=chkId%>" value="<%=info.getAssetsNo()%>"></td>
<td><%=info.getAssetsNo()%></td>
<td><%=info.getSerialNo()%></td>
<td><%=info.getAssetsName()%></td>
<td><%=info.getAssetsClass()%></td>
<td><%=info.getCgTime()%></td>
<td><%=info.getGbTime()%></td>
<td><%=info.getConfigInfo()%></td>
</tr>
<%
}
%>
</tbody>
</table>
<script>
(() => {
const table = document.getElementById('resultTable');
const checkAll = document.getElementById('checkAll');
const rowChecks = table.querySelectorAll('.row-check');
// 1. 行點擊切換高亮(排除 checkbox 自身點擊,避免雙重切換)
table.addEventListener('click', e => {
const tr = e.target.closest('tr[data-id]');
if (!tr) return;
// 若點擊的是 checkbox,由 change 事件處理,這裡不再 toggle
if (e.target.type === 'checkbox') return;
tr.classList.toggle('selected');
const cb = tr.querySelector('.row-check');
if (cb) cb.checked = tr.classList.contains('selected');
updateCheckAll();
});
// 2. Checkbox 變化同步行高亮
rowChecks.forEach(cb => {
cb.addEventListener('change', () => {
cb.closest('tr').classList.toggle('selected', cb.checked);
updateCheckAll();
});
});
// 3. 全選/反選
checkAll.addEventListener('change', () => {
const checked = checkAll.checked;
rowChecks.forEach(cb => {
cb.checked = checked;
cb.closest('tr').classList.toggle('selected', checked);
});
});
function updateCheckAll() {
const checkedCount = table.querySelectorAll('.row-check:checked').length;
checkAll.checked = checkedCount === rowChecks.length && rowChecks.length > 0;
checkAll.indeterminate = checkedCount > 0 && checkedCount < rowChecks.length;
}
// 4. 獲取已選 ID(提交時用)
window.getSelectedIds = () =>
Array.from(table.querySelectorAll('.row-check:checked')).map(cb => cb.value);
})();
</script>
</body>
</html>
table 上綁一個 click,動態新增行無需重綁。e.target.closest('tr[data-id]'):向上查找最近的行,兼容點擊 td、span 等內部元素。.selected 決定,易維護、可主題化。checked 屬性。// 單選:點擊行時取消其他行選中
table.addEventListener('click', e => {
const tr = e.target.closest('tr[data-id]');
if (!tr || e.target.type === 'checkbox') return;
// 取消其他
table.querySelectorAll('tr.selected').forEach(r => {
r.classList.remove('selected');
r.querySelector('.row-check').checked = false;
});
// 選中當前
tr.classList.add('selected');
tr.querySelector('.row-check').checked = true;
updateCheckAll();
});
onclick="check(this, ...)":內聯 JS 難維護、易 XSS、混淆 Java/JS 邏輯。document.getElementById(rwid).style.background = 'blue' 內聯樣式:覆蓋 hover、難復用、違反關注點分離。data-id 屬性,提交時直接 Array.from(...).map(cb => cb.value) 獲取選中值。用 **事件委託 + CSS 類名 + data-* 屬性** 替代內聯 onclick + style 操作,代碼更乾淨、性能更好、易於擴展(如增加鍵盤導航、範圍選中 Shift+Click 等)。