在我的html页面,它第一次很好。
就像http://jsfiddle.net/pzCcE/1/
有人可以帮我改进吗?
<table id="tab1"> <input type="checkBox" name="checkAll" id="checkAll">全選 <input type="checkBox" name="book" id="book" value="book1">book1 <input type="checkBox" name="book" id="book" value="book2">book2 <input type="checkBox" name="book" id="book" value="book3">book3 <input type="checkBox" name="book" id="book" value="book4">book4 <input type="checkBox" name="book" id="book" value="book5">book5</table> $(function () { $("#tab1 #checkAll").click(function () { if ($("#tab1 #checkAll").is(':checked')) { $("#tab1 input[type=checkBox]").each(function () { $(this).attr("checked",true); }); } else { $("#tab1 input[type=checkBox]").each(function () { $(this).attr("checked",false); }); } }); });
解决方法
$(this).attr("checked",true);
至
$(this).prop("checked",true);
实际上我刚刚回答了另一个类似于此的问题。根据.prop()文档:
The .prop() method is a convenient way to set the value of
properties—especially when setting multiple properties,using values
returned by a function,or setting values on multiple elements at
once. It should be used when setting selectedIndex,tagName,nodeName,
nodeType,ownerDocument,defaultChecked,or defaultSelected. Since
jQuery 1.6,these properties can no longer be set with the .attr()
method. They do not have corresponding attributes and are only
properties.Properties generally affect the dynamic state of a DOM element without
changing the serialized HTML attribute. Examples include the value
property of input elements,the disabled property of inputs and
buttons,or the checked property of a checkBox. The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value.