DIV CSS 佈局教程網

解決 jQuery 操作 checkbox 在火狐下第二次無法勾選的問題
編輯:JQuery入門技巧     

最近在學習 jQuery(版本 jquery-1.9.1.js),需要實現全選/全不選、反選的功能。這段程式碼在 IE8 中運作正常,但在 Firefox 中卻出現了莫名其妙的小問題,達不到預期效果。

HTML 程式碼如下:

<div>
  你愛好的運動是
  <input type="checkbox" id="selectal1" /><label for="selectal1">全選/全不選</label><br/>
  <input name="intrest" type="checkbox" />足球
  <input name="intrest" type="checkbox" />籃球
  <input name="intrest" type="checkbox" />羽毛球
  <input name="intrest" type="checkbox" />乒乓球<br/>
  <button id="allbtn">全選</button>
  <button id="notallbtn">全不選</button>
  <button id="reversebtn">反選</button>
  <button>提交</button>
</div>

最初使用的 jQuery 程式碼(以 attr 操作):

<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript">
$().ready(function(){
    // 全選/全不選復選框
    $("#selectal1").click(function(){
        if($(this).attr("checked") == true){
            $("input:checkbox[id!='selectal1']").each(function(){ $(this).attr("checked", true); });
        }else{
            $("input:checkbox[id!='selectal1']").each(function(){ $(this).attr("checked", false); });
        }
    });
    // 全選按鈕
    $("#allbtn").click(function(){
        $("input:checkbox[id!='selectal1']").each(function(){ $(this).attr("checked", true); });
    });
    // 全不選按鈕
    $("#notallbtn").click(function(){
        $("input:checkbox[id!='selectal1']").each(function(){ $(this).attr("checked", false); });
    });
    // 反選按鈕
    $("#reversebtn").click(function(){
        $("input:checkbox[id!='selectal1']").each(function(){ $(this).attr("checked", !$(this).attr("checked")); });
    });
})
</script>

問題現象:復選框綁定了 click 事件,點一次選中、再點一次取消,這個邏輯在 IE8 中沒問題。但在 Firefox 中測試時,前兩次都正常,可當再次嘗試勾選時,復選框的 checked 屬性值確實變成了「checked」,卻遲遲不顯示勾選狀態。一開始我以為是瀏覽器快取的問題,但清除快取後仍然無效。

後來在網上查到,這其實是 jQuery 版本導致的相容性問題:jQuery 1.6 以上版本使用 attr 會存在相容性問題,需要改用 prop。

查了 API 後得知,prop 的語法為 prop(name|properties|key,value|fn),用來獲取或設定匹配元素集合中第一個元素的屬性值。jQuery 官方 API 明確指出,1.6 以上版本應使用 prop,尤其是對 checkbox 的 checked 屬性進行判斷時。

修正後的程式碼

// 1.6+ 的 jQuery 要用 prop 代替 attr,否則達不到效果
// 全選/全不選復選框
$("#selectal1").click(function(){
    if($(this).prop("checked") == true){
        $("input:checkbox[id!='selectal1']").each(function(){ $(this).prop("checked", true); });
    }else{
        $("input:checkbox[id!='selectal1']").each(function(){ $(this).prop("checked", false); });
    }
});
// 全選按鈕
$("#allbtn").click(function(){
    $("input:checkbox[id!='selectal1']").each(function(){ $(this).prop("checked", true); });
});
// 全不選按鈕
$("#notallbtn").click(function(){
    $("input:checkbox[id!='selectal1']").each(function(){ $(this).prop("checked", false); });
});
// 反選按鈕
$("#reversebtn").click(function(){
    $("input:checkbox[id!='selectal1']").each(function(){ $(this).prop("checked", !$(this).prop("checked")); });
});

把 attr 全部換成 prop 之後,火狐下的勾選問題就迎刃而解了。這個案例提醒我們:處理 checkbox 的選中狀態等「動態屬性」時,應優先使用 prop。

以上就是本文的全部內容,希望對大家的學習有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved