萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 操作 Checkbox 全選/反選在 Firefox 失效的原因與修正方案

早期 jQuery 版本中,使用 .attr("checked", true/false) 或 .removeAttr("checked") 操作 checkbox 在 Firefox 下表現異常 (全選後反選失效、狀態不同步)。根因在於 **Attribute (屬性) 與 Property (屬性) 的混淆**。本文解析原因並給出跨瀏覽器穩健方案。

問題重現代碼

// ❌ 錯誤示範:attr 操作 attribute,不改變 DOM property
$("#checkAll").click(function(){
    $("input[type='checkbox']").attr("checked", true); // 全選
});

$("#invert").click(function(){
    $("input[type='checkbox']").each(function(){
        if ($(this).attr("checked")) { // 讀取 attribute
            $(this).removeAttr("checked"); // 移除 attribute
        } else {
            $(this).attr("checked", "checked");
        }
    });
});

根因分析

  • checked 是 **Boolean Property** (IDL 屬性),決定當前勾選狀態。
  • checked **Attribute** (HTML 屬性) 僅表示**默認值** (defaultChecked)。
  • jQuery 1.6+ 強制區分:.prop() 操作 Property,**.attr() 僅操作 Attribute**。
  • Firefox 嚴格遵循規範:.attr("checked", true) 只添加 HTML 屬性,不改變 Property,導致 UI 不變、提交值為 off。
  • IE 早期版本模糊處理,偶然「生效」掩蓋了 Bug。

正確寫法 (jQuery 1.6+ / 現代版本)

// ✅ 全選
$("#checkAll").click(function(){
    $("input[type='checkbox']").prop("checked", true);
});

// ✅ 取消全選
$("#uncheckAll").click(function(){
    $("input[type='checkbox']").prop("checked", false);
});

// ✅ 反選 (兩種寫法)
$("#invert").click(function(){
    // 寫法 A:原生 property 切換 (最快、最穩)
    $("input[type='checkbox']").each(function(){
        this.checked = !this.checked;
    });
    
    // 寫法 B:jQuery prop + 回調函數
    $("input[type='checkbox']").prop("checked", function(i, val){
        return !val;
    });
});

// ✅ 獲取選中值
var vals = $("input[type='checkbox']:checked").map(function(){ return this.value; }).get();

原生 JS 方案 (零依賴、最高性能)

// 全選
function checkAll(name, flag = true) {
    document.querySelectorAll(`input[name="${name}"]`).forEach(el => el.checked = flag);
}

// 反選
function toggleAll(name) {
    document.querySelectorAll(`input[name="${name}"]`).forEach(el => el.checked = !el.checked);
}

// 獲取選中值
function getCheckedValues(name) {
    return [...document.querySelectorAll(`input[name="${name}"]:checked`)].map(el => el.value);
}

最佳實踐總結

  1. 永遠使用 .prop() 操作 checked/disabled/selected/readonly 等布爾屬性。
  2. 讀取狀態用 :checked 選擇器或 .prop("checked"),勿用 .attr("checked")。
  3. 反選/切換優先用原生 el.checked = !el.checked**,無庫依賴、語義明確、性能最優。
  4. 事件委託:大量 checkbox 時,綁定在父容器 change 事件,通過 e.target.matches('input[type="checkbox"]') 判斷。

理解 Attribute vs Property 區別是前端進階必修課,能徹底解決 checkbox、select、input 狀態同步的各種疑難雜症。

copyright © 萬盛學電腦網 all rights reserved