最近作checkbox,遇到一個奇葩問題,以下:javascript
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="jquery-1.9.1.js"></script> </head> <body> <input type="button" value="all" id="selall"> <input type="checkbox" name="sel[]" value="1">1 <input type="checkbox" name="sel[]" value="2">2 <input type="checkbox" name="sel[]" value="3">3 <script type="text/javascript"> $(function(){ var chk = false, sel = $('input[name^="sel"]'); $('#selall').click(function(){ if(chk){ chk = false; sel.attr('checked', false); }else{ chk = true; sel.attr('checked', true); } }) }) </script> </body> </html>
以上代碼chrome中,點擊button 全選,再點擊全不選。一切正常,可是第三次點擊,就罷工了。F12查看,發現checked屬性是修改了的,就是說添加了 checed="checked",可是未顯示勾。html
檢查代碼,沒有問題啊。難道是兼容問題,因而換了firefox,問題依舊。以後又換了IE,竟然正常了!! 沒錯IE正常,這是要逆襲的節奏?不能啊……因而查看jquery API,在.attr()中中間一點,吐槽完IE後,有這麼一段話java
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.jquery
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr()
method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop()
method provides a way to explicitly retrieve property values, while .attr()
retrieves attributes.chrome
就是說jquery 1.6+,使用attr(),獲取未定義的屬性將返回undefined .檢索和修改DOM的特性(property), 如表單元素的checked,selected,或disabled狀態,使用prop()方法 api
因而替換attr()爲prop(),簡化下代碼 改成:ide
var sel = $('input[name^="sel"]'); $('#selall').click(function(){ if(! $(this).prop('checked')){ sel.prop('checked', false); }else{ sel.prop('checked', true); } })
最後,吐槽下! IE你果真是個大坑……this