jQuery中的attr()和prop()使用

总结:除了checked、seleted这样的属性推荐用prop()外,其他的随意都可以。

原因如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
    <script type="text/javascript" src="../js/lib/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        function testCheck() {
            var result1 = $("#check").prop("checked"); //结果是true
            var result2 = $("#check").attr("checked"); //结果是checked
            console.info("被选择的情况下" + "result1:" + result1 + "||result2:" + result2);
        }
        function testNoCheck() {
            var result1 = $("#nocheck").prop("checked"); //结果是false
            var result2 = $("#nocheck").attr("checked"); //结果是undefined
            console.info("未有选择的情况下" + "result1:" + result1 + "||result2:" + result2);
        }

        $(function () {
            testCheck();//被选择的情况下result1:true||result2:checked
            testNoCheck();//未有选择的情况下result1:false||result2:undefined
        })
    </script>
</head>
<body>
<input id="check" type="checkbox" value="football" checked="checked">足球
<input id="nocheck" type="checkbox" value="football">篮球
</body>
</html>

说明:

prop()对于seleted返回的是true或者false,更直观。