jquery 1.6+ 獲取checkbox的checked屬性總是checked

項目中用的jquery1.9 今天需要檢測一個checkbox的選中狀態,想當然的用 .attr("checked") ,結果發現,無論是否選中,這個值都是 undefined 未定義。

折騰了半天,無奈,只能取jq官網看看文檔,發現有這麼一段說明

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop()method.

注意最後兩句話,說什麼.attr() 不能用於普通對象,數組,窗口,文檔什麼玩意的,要重新獲取改變dom屬性,用.prop()方法。

ok,雖然不太明白它說的具體含義是什麼,但是看到.prop方法姑且一試吧,結果還真可以,若選中則返回true否則返回false。

代碼貼上來,有興趣可自行測試:

01 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02 <html xmlns="http://www.w3.org/1999/xhtml">
03     <head>
04         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
05         <script>
06             $(function(){
07                 $("#clk").click(function(){
08                     alert($("#ckb").prop("checked"));
09                 })
10             })
11         </script>
12     </head>
13     <body>
14         <input type="button" value="click" id="clk">
15         <input type="checkbox" id="ckb"/>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章