不同版本的jquery的複選框checkbox的相關問題

來源:互聯網
上載者:User

標籤:style   blog   http   java   color   使用   

在嘗試寫複選框時候遇到一個問題,調試了很久都沒調試出來,極其鬱悶:

IE10,Chrome,FF中,對於選中狀態,第一次$(‘#checkbox‘).attr(‘checked‘,true)可以實現

但是當通過代碼清除選中,下次再通過代碼 $(‘#checkbox‘).attr(‘checked‘,true) 去選中時

雖然代碼中有checked=‘checked‘,但是畫面表現都沒有打勾。

例如如下的代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title></title> <!--   引入jQuery --><script src="../../scripts/jquery.js" type="text/javascript"></script> <script type="text/javascript">  $(function(){     //全選     $("#CheckedAll").click(function(){         $(‘[name=items]:checkbox‘).attr(‘checked‘, true);     });     //全不選     $("#CheckedNo").click(function(){        $(‘[type=checkbox]:checkbox‘).attr(‘checked‘, false);     });  })  </script></head><body><form method="post" action="">   你愛好的運動是?   <br/>    <input type="checkbox" name="items" value="足球"/>足球    <input type="checkbox" name="items" value="籃球"/>籃球    <input type="checkbox" name="items" value="羽毛球"/>羽毛球    <input type="checkbox" name="items" value="乒乓球"/>乒乓球   <br/>    <input type="button" id="CheckedAll" value="全 選"/>    <input type="button" id="CheckedNo" value="全不選"/>    <input type="button" id="CheckedRev" value="反 選"/>     <input type="button" id="send" value="提 交"/> </form></body></html>


後來查了查資料,發現在jquery 1.8.x中的版本,我們對於checkbox的選中與不選中操作如下:

判斷是否選中

$(‘#checkbox‘).prop(‘checked‘)

設定選中與不選中狀態:

$(‘#checkbox‘).attr(‘checked‘,true)

$(‘#checkbox‘).attr(‘checked‘,false)

 

但此方法在jquery1.9.1及其以後的版本中,就會出現如上文所示的問題,

 

後來尋找相關的資料,發現現在attr(‘checked‘,true)都換成prop(‘checked‘,true)

prop()擷取匹配的元素的屬性值。
這個方法是jquery1.6以後出來的,用來區別之前的.attr()方法.

區別最大的一點就是:布爾型的屬性,1.6以後都是用.prop()方法就好了。
這個布爾型的屬性,再解釋一下,是屬性值只有true|false的屬性。
還有種情況就是只添加屬性名稱,不需要寫屬性值的就可以生效的也同樣使用.prop()方法。比如:checked、disable這樣的,其實它們說到底還是屬於布爾型的屬性。
1.添加屬性名稱該屬性就會生效應該使用prop();
2.是有true,false兩個屬性使用prop();
3.其他則使用attr();

參考:http://blog.sina.com.cn/s/blog_655388ed01017cnc.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.