name 屬性(如 name="a")。name="aAll" 標識。value 區分。<span>第1組(a):<input type="checkbox" name="aAll" onclick="chkAll(this)" />全選/全不選</span>
<input type="checkbox" name="a" value="a1" checked> a1
<input type="checkbox" name="a" value="a2"> a2
<input type="checkbox" name="a" value="a3"> a3
<input type="checkbox" name="a" value="a4"> a4
function chkAll(obj) {
// obj 為「全選」checkbox 本身
var groupName = $(obj).attr('name').substring(0, 1); // 取首字母 'a'/'b'/'c'
// 通用寫法:直接操作 DOM 屬性,兼容所有 jQuery 版本
$(':checkbox[name="' + groupName + '"]').each(function() {
this.checked = obj.checked; // 原生屬性賦值,最高效兼容
});
}
function getCheckboxValues(name) {
return $(':checkbox[name="' + name + '"]:checked').map(function() {
return $(this).val();
}).get().join(',');
}
function getValues() {
var aV = getCheckboxValues('a');
var bV = getCheckboxValues('b');
var cV = getCheckboxValues('c');
alert('a組: ' + (aV || '未選中') + '\nb組: ' + (bV || '未選中') + '\nc組: ' + (cV || '未選中'));
}
| jQuery 版本 | 設置 checked 推薦寫法 |
|---|---|
| ≥ 1.6 | $(...).prop('checked', true/false) |
| < 1.6 | $(...).attr('checked', true/false) |
| 所有版本通用 | element.checked = true/false (原生 DOM 屬性) |
結論:直接操作 this.checked 最簡潔、最高效、零版本依賴。
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script>
function chkAll(obj) {
var name = $(obj).attr('name').charAt(0);
$(':checkbox[name="' + name + '"]').each(function() { this.checked = obj.checked; });
}
function getCheckboxValues(name) {
return $(':checkbox[name="' + name + '"]:checked').map(function() { return this.value; }).get().join(',');
}
function getValues() {
alert('a:' + (getCheckboxValues('a')||'無') + '\nb:' + (getCheckboxValues('b')||'無') + '\nc:' + (getCheckboxValues('c')||'無'));
}
</script>
function chkAllNative(obj) {
var name = obj.name.slice(0, -3); // 去掉 "All"
document.querySelectorAll('input[type="checkbox"][name="' + name + '"]').forEach(el => el.checked = obj.checked);
}