jquery 獲取checkbox的checked屬性總是undefined


項目中用的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。

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

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
        <script>
            $(function(){
                $("#clk").click(function(){
                    alert($("#ckb").prop("checked"));
                })
            })
        </script>
    </head>
    <body>
        <input type="button" value="click" id="clk">
        <input type="checkbox" id="ckb"/>
    </body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM