jquery 對 checkbox 的 全選、反選、全不選等操作
阿新 • • 發佈:2019-02-06
jquery對checkbox的一些操作,比如選中,全選,反選,全不選等,通常我們會用到attr來改變checkbox的checked屬性,然而通過實際測試,會出現各種小問題,例如第一次成功,第二次就不成功,除錯也調不出來,說白了就是第二次的是attr方法未起到效果。經過查閱文件資料,最終確定使用prop 方法能徹底解決此問題,程式碼如下:
function countCheckbox() {//統計選中checkbox的數量 var mainPageCheckbox = $("input[name=main_page_checkbox]"); var count = 0; mainPageCheckbox.each(function() { if ($(this).is(':checked')) { count++; } }); $("#pageCheckCount").html(count); } function pageSelectAll() {//全選 var mainPageCheckBox = $("input[name=main_page_checkbox]"); mainPageCheckBox.each(function(){ $(this).prop("checked", true); }); countCheckbox(); } function pageNoSelectAll() {//不全選 var mainPageCheckBox = $("input[name=main_page_checkbox]"); mainPageCheckBox.each(function(){ $(this).prop("checked", false); }); countCheckbox(); } function pageUnselected() {//反選 var mainPageCheckBox = $("input[name=main_page_checkbox]"); mainPageCheckBox.each(function(){ $(this).prop("checked", !$(this).is(':checked'));//注意這裡用的是 prop 而不是 attr }); countCheckbox(); }