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>
原文地址:https://www.cnblogs.com/jsonzheng/p/3655874.html