全選/反選是列表頁最常見的需求之一。下面這份範例示範如何把切換邏輯寫成一個可重複使用的 jQuery 外掛,而不是散落在各處的 if 判斷。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
#newsTable{margin:100px auto;}
</style>
<script language="javascript" type="text/javascript" src="jquery1.1.2.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$("#btnOk").click(function(){
this.value = this.value == "全選" ? "反選" : "全選";
$("input[@type='checkbox']").checkCbx();
});
});
// 當你的程式碼出現 each 時,就該考慮把它重寫成外掛
$.fn.checkCbx = function(){
return this.each(function(){
this.checked = !this.checked;
});
}
</script>
<title>全選與反選範例</title>
</head>
<body>
<table border="1" id="newsTable">
<tr>
<th>選擇</th>
<th>Id</th>
<th>作者</th>
</tr>
<tr>
<td><input type="checkbox" name="cbx" /></td>
<td>1</td>
<td>阿會楠</td>
</tr>
<tr>
<td><input type="checkbox" name="cbx" /></td>
<td>2</td>
<td>阿會楠</td>
</tr>
<tr>
<td><input type="checkbox" name="cbx" /></td>
<td>3</td>
<td>阿會楠</td>
</tr>
<tr>
<td><input type="checkbox" name="cbx" /></td>
<td>4</td>
<td>阿會楠</td>
</tr>
<tr>
<td><input type="checkbox" name="cbx" /></td>
<td>5</td>
<td>阿會楠</td>
</tr>
<tr>
<td><input type="checkbox" name="cbx" /></td>
<td>6</td>
<td>阿會楠</td>
</tr>
<tr>
<td colspan="3"><input type="button" name="btnOk" id="btnOk" value="全選" /></td>
</tr>
</table>
</body>
</html>
$.fn.checkCbx 就是 jQuery 外掛的標準寫法:把函式掛到 $.fn(也就是 jQuery.prototype)上,之後所有 jQuery 物件都能呼叫 checkCbx()。
函式內部 return this.each(...) 有兩個作用:一是對集合中每個元素逐一反轉 checked 狀態;二是回傳 this,讓鏈式呼叫不會中斷。這正是 jQuery 官方建議的直覺法則——每當程式碼裡出現 each,就該想想能不能抽成外掛。
按鈕文字則用三元運算子在「全選」與「反選」之間切換,讓使用者知道下一次點擊會做什麼。
範例中的 input[@type='checkbox'] 屬於 jQuery 1.1.x 的老寫法。在 1.2 以上版本中,@ 符號已移除,應寫成 $("input:checkbox") 或 $("input[type=checkbox]")。