遍歷所有行(tr),針對每行的指定單元格(td/th)設置樣式。關鍵點:動態數據必須先渲染再隱藏,否則新增行不受影響。
<table id="mytable">
<thead>
<tr>
<th>日期</th><th>媒體</th><th>曝光</th><th class="hide-guest">CTR</th><th class="hide-guest">跳出率</th>
</tr>
</thead>
<tbody id="detail_id"></tbody>
</table>
<script>
// 權限控制:guest 隱藏敏感列
if (uname === "guest") {
// 方式 1:CSS 類控制(推薦,易維護)
$("#mytable .hide-guest").hide();
// 方式 2:直接操作 style(兼容無類場景)
// $("#mytable tr").each(function() {
// $(this).find("td:eq(3), td:eq(4), th:eq(3), th:eq(4)").css("display", "none");
// });
}
// 動態渲染數據後調用
function renderTable(data) {
const html = data.map(row => `<tr><td>${row.date}</td>...</tr>`).join("");
$("#detail_id").html(html);
applyPermission(); // 重新應用權限
}
<style>
:root {
--col-sensitive: table-cell; /* 默認顯示 */
}
.hide-sensitive --col-sensitive: none; /* 隱藏 */
#mytable td.sensitive,
#mytable th.sensitive {
display: var(--col-sensitive);
}
</style>
<script>
// 權限切換只需切換容器類名
function applyPermission(role) {
document.getElementById("mytable").classList.toggle("hide-sensitive", role === "guest");
}
</script>
<style>
/* 手機隱藏標記為 secondary 的列 */
@media (max-width: 768px) {
#mytable td.secondary,
#mytable th.secondary {
display: none;
}
}
</style>
<th class="secondary">訪問深度</th>
<td class="secondary">...</td>
transform: translateY 實現虛擬列表Map<columnIndex, boolean>aria-hidden="true")