四個同名 Checkbox,僅選中 value="checkbox3" 時彈窗提示。
$(document).on('change', 'input[name="checkbox"]', function() {
if (this.checked && this.value === 'checkbox3') {
alert('選中 checkbox3');
}
});
change 而非 click:鍵盤空白鍵、標籤點擊、程式碼 prop('checked', true) 皆觸發 change,覆蓋面更全。$(document).on(...):動態新增的 Checkbox 自動生效,效能優於逐個綁定。this.value === 'checkbox3':嚴格相等避免型別轉換陷阱;this 指向原生 DOM 元素,直接取屬性最快。if (this.checked ...) 確保僅勾選時觸發。
document.addEventListener('change', e => {
if (e.target.matches('input[name="checkbox"]') && e.target.checked && e.target.value === 'checkbox3') {
alert('選中 checkbox3');
}
});