2013-10-04 28 views
0

我有一張表,代表所有CMS帖子。 我正在寫一個功能,允許通過單擊「全部選中/取消全選」來選擇/取消選擇所有帖子checkbox element按預期選擇元素,但只有一次,爲什麼?

例如,這將按預期工作 - 無論您點擊多少次。 如果複選框被選中 - 它會提醒「檢查所有現在被選中」 否則 - 它會提醒「檢查所有沒有被選中,現在」

$("table thead input").click(function(){ 

var checkboxes = $("table tbody tr input") 

if ($(this).is(':checked')) { 

    alert('Check All is checked now'); 
} else { 

    alert('Check All is UNchecked now'); 
    } 
}); 

再次 - 它按預期工作。

但是,如果用另一個邏輯替換alert() s,則不再按預期方式工作,而只是一次。

$("table thead input").click(function(){ 

var checkboxes = $("table tbody tr input") 

    if ($(this).is(':checked')) { 

    checkboxes.each(function(){ 
    $(this).attr('checked', true); 
    }); 

    } else { 

    checkboxes.each(function(){ 

    $(this).attr('checked', false); 
    }); 
    } 
}); 

它會檢查/取消那些checboxes,但只有一次 - 如果你點擊$("table thead input")多於一次,它不會工作。

我試過,以removeAttr('checked')而不是$(this).attr('checked', false),但沒有運氣。

有什麼問題?

回答

1

使用.prop()代替.attr()設置選中狀態

$(this).prop('checked', false);//to uncheck 
$(this).prop('checked', true);//to check 

Attributes vs Properties

您的代碼可以簡化爲

$("table thead input").change(function() { 
    var checkboxes = $("table tbody tr input"); 
    checkboxes.prop('checked', this.checked) 
}); 

或者下面,如果元素不是動態的

//cache the checkbox reference 
var checkboxes = $("table tbody tr input"); 
$("table thead input").change(function() { 
    checkboxes.prop('checked', this.checked) 
}); 
相關問題