$("#choice").bind("change",function(){ $("input[type='checkbox']").attr("checked", $("#choice").attr("checked")); });
使用上述代码最全选/取消全选时发现,$("#choice").attr("checked")报告undefined,于是将控制元素设置上属性checked,这是发现无论如何,$("#choice").attr("checked")的值都为true。于是查阅http://api.jquery.com/attr/发现其中有如下描述:
As of jQuery 1.6, the .attr() method returns undefined for attributes that have
not been set. To retrieve and change DOM properties such as the checked,
selected, or disabled state of form elements, use the .prop() method.
于是调整代码如下:
$("#choice").bind("change",function(){ $("input[type='checkbox']").prop("checked", $("#choice").prop("checked")); });
在firefox、opera、safari、chrome、IE7-9中测试通过。