核心需求
- 針對同
name 的核取方塊群組操作
- 即時獲取選中項目的值與數量
- 動態顯示選擇結果
完整程式碼 (現代化重構)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery 核取方塊群組操作</title>
<style>
.container { max-width: 500px; margin: 40px auto; padding: 20px; font-family: sans-serif; }
.checkbox-group { display: flex; gap: 20px; flex-wrap: wrap; margin: 20px 0; }
.checkbox-item { display: flex; align-items: center; gap: 8px; cursor: pointer; padding: 8px 12px; border: 1px solid #e0e0e0; border-radius: 4px; transition: all 0.2s; }
.checkbox-item:hover { border-color: #1976d2; background: #e3f2fd; }
.checkbox-item input { accent-color: #1976d2; width: 18px; height: 18px; }
#result { padding: 16px; background: #f5f5f5; border-radius: 8px; font-size: 16px; line-height: 1.6; min-height: 60px; }
.count { color: #1976d2; font-weight: bold; font-size: 1.2em; }
.values { color: #333; margin-top: 8px; }
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container">
<h2>興趣愛好選擇</h2>
<div class="checkbox-group" id="loveGroup">
<label class="checkbox-item"><input type="checkbox" name="love" value="Football"> 足球</label>
<label class="checkbox-item"><input type="checkbox" name="love" value="Basketball"> 籃球</label>
<label class="checkbox-item"><input type="checkbox" name="love" value="Volleyball"> 排球</label>
<label class="checkbox-item"><input type="checkbox" name="love" value="Swimming"> 游泳</label>
<label class="checkbox-item"><input type="checkbox" name="love" value="Running"> 跑步</label>
<label class="checkbox-item"><input type="checkbox" name="love" value="Cycling"> 騎行</label>
</div>
<div id="result">
<div>您選擇了 <span class="count" id="count">0</span> 項愛好</div>
<div class="values" id="values">內容:無</div>
</div>
</div>
<script>
$(function() {
const $group = $('#loveGroup');
const $count = $('#count');
const $values = $('#values');
// 事件委派:群組層級監聽 change 事件
$group.on('change', 'input[name="love"]', function() {
updateDisplay();
});
function updateDisplay() {
// 核心:取得所有被選中的核取方塊
const $checked = $group.find('input[name="love"]:checked');
const count = $checked.length;
const values = $checked.map(function() { return this.value; }).get(); // 取得原生陣列
$count.text(count);
$values.html(count > 0 ? `內容:${values.join('、')}` : '內容:無');
}
// 程式化操作示範
window.checkAll = () => $group.find('input[name="love"]').prop('checked', true).trigger('change');
window.uncheckAll = () => $group.find('input[name="love"]').prop('checked', false).trigger('change');
});
</script>
</body>
</html>
關鍵 API 深度解析
1. 選擇器 :checked 僅匹配勾選狀態
// 正確:僅選取被勾選的
$('input[name="love"]:checked')
// 錯誤:選取所有同 name 的,無論勾選與否
$('input[name="love"]')
2. .map() 取值轉陣列
// 返回 jQuery 物件包裹的陣列
const $vals = $checked.map(function() { return this.value; });
// .get() 解包為原生陣列 ['Football', 'Basketball']
const arr = $vals.get();
3. .prop() vs .attr() 設定勾選狀態
| 方法 | 用途 | 範例 |
.prop('checked', true) | 設定/讀取 屬性狀態 (布林值) | 動態勾選/取消勾選 ✅ |
.attr('checked', 'checked') | 設定/讀取 HTML 屬性 (字串) | 初始 HTML 渲染時的默認值 |
鐵律:動態操作布林屬性 (checked, disabled, selected, readonly) 一律用 .prop()。
進階模式:全選/反選/取值
// 全選
$('#btnAll').on('click', () => {
$group.find('input[name="love"]').prop('checked', true).trigger('change');
});
// 反選
$('#btnInvert').on('click', () => {
$group.find('input[name="love"]').each(function() {
this.checked = !this.checked; // 原生 DOM 切換最快
}).trigger('change');
});
// 獲取值陣列 (供表單提交)
function getSelectedValues() {
return $group.find('input[name="love"]:checked').map((_, el) => el.value).get();
}
// 設定預選值 (陣列)
function setSelectedValues(values) {
const valSet = new Set(values);
$group.find('input[name="love"]').each(function() {
this.checked = valSet.has(this.value);
}).trigger('change');
}
無障礙與 UX 增強
- 使用
<label> 包裹 <input>,點擊文字即可切換
accent-color CSS 自定義核取方塊顏色 (現代瀏覽器)
- 群組用
<fieldset> + <legend> 語意化
- 鍵盤操作:Tab 聚焦、Space 切換、方向鍵移動焦點
總結
掌握 :checked 選擇器、.prop() 狀態操作、.map().get() 取值轉陣列、事件委派模式,即可輕鬆處理任何核取方塊群組交互需求。
copyright ©
萬盛學電腦網 all rights reserved