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

總結:除了checked、seleted這樣的屬性推薦用prop()外,其餘的隨意均可以。

緣由以下:javascript

<!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>

說明:html

prop()對於seleted返回的是true或者false,更直觀。java

相關文章
相關標籤/搜索