Jquery选中表中的所有复选框

我有一个脚本应该检查表中的所有复选框。 它会在第一次检查它们,然后在它之后取消选中它们。 但是,当我试图重新检查时,没有任何反应。

jquery:

$('#selectAll').click(function(e){ var table= $(e.target).closest('table'); $('td input:checkbox',table).attr('checked',e.target.checked); }); 

HTML:

 
hi!
hi!
hi!

这是行为的小提琴:

http://jsfiddle.net/EEJrU/

单击一次后为什么不起作用?

你需要使用.prop()而不是.attr()

 $('#selectAll').click(function(e){ var table= $(e.target).closest('table'); $('td input:checkbox',table).prop('checked',this.checked); }); 

演示: 小提琴

属性与属性

       
Cell phone Rating
BlackBerry Bold 9650 2/5
Samsung Galaxy 3.5/5
Droid X 4.5/5
HTC Desire 3/5
Apple iPhone 4 5/5

这可能对prop()和attr()之间的区别很有用。 请注意本文中的这一行.prop()vs .attr() :

“属性值反映了默认值而不是当前可见状态(除了IE的某些旧版本,因此使事情变得更难)。该属性不会告诉您是否检查了页面上的复选框。”

所以一般来说,使用prop()而不是attr()。

简单的jQuery解决方案,检测表内的已检查输入,以及main(selectAll)复选框的状态更改:

 
Email Join date
example@gmail.com 21 Oct, 2016 at 11:29 pm
example@gmail.com 21 Oct, 2016 at 11:29 pm
$(document).ready(function() { var $selectAll = $('#selectAll'); // main checkbox inside table thead var $table = $('.table'); // table selector var $tdCheckbox = $table.find('tbody input:checkbox'); // checboxes inside table body var $tdCheckboxChecked = []; // checked checbox arr //Select or deselect all checkboxes on main checkbox change $selectAll.on('click', function () { $tdCheckbox.prop('checked', this.checked); }); //Switch main checkbox state to checked when all checkboxes inside tbody tag is checked $tdCheckbox.on('change', function(){ $tdCheckboxChecked = $table.find('tbody input:checkbox:checked');//Collect all checked checkboxes from tbody tag //if length of already checked checkboxes inside tbody tag is the same as all tbody checkboxes length, then set property of main checkbox to "true", else set to "false" $selectAll.prop('checked', ($tdCheckboxChecked.length == $tdCheckbox.length)); }) });

演示: jsfiddle