「隱藏表格裡的第 N 行之後的所有列」是極常見的需求,例如略過表頭、隱藏小計列。jQuery 提供了多種路徑,選哪一種取決於你的 HTML 是否可控。
最直觀,也最常用。在組裝 HTML 時動態產生 id,之後用迴圈控制:
<table> <tr><td>這行不隱藏</td></tr> <tr id="tr_1"><td>這行要隱藏</td></tr> <tr id="tr_2"><td>這行要隱藏</td></tr> ... </table>
for (var i = 1; i < tr_len; i++) { // tr_len 為要控制的 TR 數量
$("#tr_" + i).hide();
}
不必為每一行取名字,只要表格本身有 id:
<table id="Tbl"> <tr><td>這行不隱藏</td></tr> <tr><td>這行要隱藏</td></tr> <tr><td>這行要隱藏</td></tr> </table>
$.each($("#Tbl tr"), function (i) {
if (i > 0) { this.style.display = 'none'; }
});
注意回調裡的 this 是原生 DOM 元素,因此不能直接呼叫 hide(),否則得寫 $(this).hide()。
替需要控制的行掛一個標記 class,再用屬性選擇器撈出來:
<table id="Tbl"> <tr><td>這行不隱藏</td></tr> <tr><td class="hid">這行要隱藏</td></tr> <tr><td class="hid">這行要隱藏</td></tr> </table>
var trs = $("tr.hid"); // 語意等同 $("tr[class='hid']"),但更快
trs.each(function () {
this.style.display = "none"; // 此處 this 為 DOM 物件,不能用 hide()
});
要還原顯示,把 hide() 換成 show(),或把 display 設為空字串即可。實務上我偏好寫 $("tr.hid").hide(),讓 jQuery 幫你保存原始的 display 值,之後 show() 能正確還原,直接動 style.display 則可能把原本 table-row 的設定弄丟。
需求是:預設顯示「對應頁面名稱」那一列;選擇「內部鏈接」時顯示頁面下拉選單,選擇「外部鏈接」時改顯示輸入框。
<tr>
<td class="tr_title_edit">
<label for="f_navname">對應頁面鏈接<font color="red">*</font></label>
</td>
<td class="tr_content_edit">
<input type="radio" id="f_inner" name="f_navState" value="1" checked="checked" />
<label for="f_inner">內部鏈接</label>
<input type="radio" id="f_outer" name="f_navState" value="2" />
<label for="f_outer">外部鏈接</label>
</td>
</tr>
<tr id="il">
<td class="tr_title_edit"><label for="f_pagename">對應頁面名稱</label></td>
<td class="tr_content_edit">
<select name="f_pageid" id="f_pageid">
<option value=""></option>
<option value="">新聞</option>
<option value="">通知</option>
</select>
</td>
</tr>
<tr id="ol" style="display:none">
<td class="tr_title_edit"><label for="f_navname">外部鏈接</label></td>
<td class="tr_content_edit">
<input type="text" class="inputLine" size="40" id="f_outsidelink" name="f_outsidelink" />
</td>
</tr>
$("input[name='f_navState']").click(function () {
$("input[name='f_navState']").each(function (i) {
if (this.checked) {
var f_navState = $("input[name='f_navState']")[i].value;
if (f_navState == 1) {
$("#il").show();
$("#ol").hide();
} else {
$("#ol").show();
$("#il").hide();
}
}
});
});
這段可以更精簡。既然觸發者本身就是被選中的 radio,直接讀它的值即可,不必再回頭遍历一次:
$("input[name='f_navState']").click(function () {
if (this.value === "1") {
$("#il").show(); $("#ol").hide();
} else {
$("#ol").show(); $("#il").hide();
}
});
另外提醒:被隱藏欄位裡的輸入值仍會隨表單送出。若後端有必填驗證,記得在切換時一併清空或停用該欄位,否則容易出現「使用者明明沒填卻收到驗證錯誤」的困惑。