如果没有禁用,则Jquery选择all

我使用以下脚本来选择具有给定类的所有复选框。

$(document).ready(function(){ // 1 // 2 $(':checkbox.selectall').on('click', function(){ // 3 $(':checkbox[class='+ $(this).data('checkbox-name') + ']').prop("checked", $(this).prop("checked")); $(':checkbox[class='+ $(this).data('checkbox-name') + ']').trigger("change"); }); }); 

但是我遇到了问题,因为de / select all复选框能够取消选择被禁用的复选框。

我试过这个

 $(document).ready(function(){ // 1 // 2 $(':checkbox.selectall').on('click', function(){ // 3 $(':checkbox[class='+ $(this).data('checkbox-name') + !$(:disabled) + ']').prop("checked", $(this).prop("checked")); $(':checkbox[class='+ $(this).data('checkbox-name') + !$(:disabled) + ']').trigger("change"); }); }); 

但它不起作用。 我已经做了一个jsfiddle来展示问题http://jsfiddle.net/e67Fv/

嗯… interresting尝试,但你不能在选择器中使用jQuery对象,因为选择器只是一个普通的字符串。

用于排除禁用元素的选择器将是:not(:disabled) ,因此您的代码应为:

 $(document).ready(function(){ $(':checkbox.selectall').on('click', function(){ $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').prop("checked", $(this).prop("checked")); $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').trigger("change"); }); }); 

请注意,您可以链接呼叫,因此您不必两次选择项目:

 $(document).ready(function(){ $(':checkbox.selectall').on('click', function(){ $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').prop("checked", $(this).prop("checked")).trigger("change"); }); }); 

使用.not .not()函数和:disabled选择器的组合来排除这些。

 $(':checkbox[class='+ $(this).data('checkbox-name') + ']').not(':disabled').prop("checked", $(this).prop("checked")); $(':checkbox[class='+ $(this).data('checkbox-name') + ']').not(':disabled').trigger("change"); 

.not()也作为选择器存在:not() ,可以按如下方式使用:

  $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').prop("checked", $(this).prop("checked")); $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').trigger("change"); 

这是我通常做的事情:

 $(function(){ $(".selectall").live('change', function(){ if($(this).is(":checked")) { $("input:checkbox:not(:disabled)." + $(this).data('checkbox-name')).prop("checked", "true"); } else { $("input:checkbox:not(:disabled)." + $(this).data('checkbox-name')).prop("checked", "false"); } }); }); 

我希望它有帮助:)

这与原始代码不同。 它只会触发那些没有改变的变化。 我已经意识到你希望在你改变之后触发所有改变

 $(':checkbox.selectall').on('click', function(){ $(':checkbox .'+ $(this).data('checkbox-name')).not(':disabled').prop("checked", $(this).prop("checked")).trigger("change"); });