全選、取消全選、反選、批量取值——這組功能幾乎出現在每一個帶列表的後台頁面裡。用 jQuery 實現只需要幾行代碼。
<input type="checkbox" name="fruit" value="apple" />蘋果
<input type="checkbox" name="fruit" value="orange" />橘子
<input type="checkbox" name="fruit" value="banana" />香蕉
<input type="checkbox" name="fruit" value="grape" />葡萄
<input type="button" id="btn1" value="全選">
<input type="button" id="btn2" value="全不選">
<input type="button" id="btn3" value="反選">
<input type="button" id="btn4" value="選中所有奇數">
<input type="button" id="btn5" value="獲得選中的所有值">
$(function() {
$('#btn1').click(function() { // 全選
$("[name='fruit']").attr('checked', 'true');
});
$('#btn2').click(function() { // 全不選
$("[name='fruit']").removeAttr('checked');
});
$('#btn3').click(function() { // 反選
$("[name='fruit']").each(function() {
if ($(this).attr('checked')) {
$(this).removeAttr('checked');
} else {
$(this).attr('checked', 'true');
}
});
});
$("#btn4").click(function() { // 選中所有奇數項
$("[name='fruit']:even").attr('checked', 'true');
});
$("#btn5").click(function() { // 獲取所有選中項的值
var checkVal = '';
$("[name='fruit'][checked]").each(function() {
checkVal += $(this).val() + ',';
});
alert(checkVal);
});
});
[name='fruit'] 比 [name=fruit] 更穩妥,遇到特殊字符時不會出錯。:even 匹配下標 0、2、4……,也就是人類直覺裡的第 1、3、5 項。上面代碼選中的是蘋果和香蕉,而不是橘子。這個反直覺的命名坑了很多人。each 逐個判斷是最清晰的方案。checkVal.slice(0, -1) 或改成數組 push 再 join(',')。上面用的是 attr('checked', 'true') 這種經典寫法。從 jQuery 1.6 開始,checked 屬於「動態屬性」,推薦改用 .prop('checked', true) 讀寫;而在 jQuery 3.x 中,attr 操作 checked 的行為已不可靠,新項目請統一使用 prop():
$("[name='fruit']").prop('checked', true); // 全選
$("[name='fruit']").prop('checked', false); // 全不選
$("[name='fruit']").filter(':checked").each(function() { ... });
另外别忘了:使用 jQuery 之前必須先引入 jQuery 包。