.attr() 與 .prop() 的差異
範例原始碼如下
<!DOCTYPE html> <html> <head> <script src="//code.jquery.com/jquery-2.1.1.min.js"></script> </head> <body> <form action="demo_form.asp"> <input type="checkbox" name="vehicle" value="Bike" checked="checked"> I have a bike<br> <input type="checkbox" name="vehicle" value="Car"> I have a car<br> <input type="checkbox" name="vehicle" value="Boat"> I have a boat<br> <input type="submit" value="Submit"> </form> </body> </html>
一、.attr()
.attr()的用法為取指定選擇子符合條件的第一個元素
基本用法為
$("input").attr("value");回傳結果為Bike
除了回傳值之外jQuery還有設定值的方法。
另外再考慮個特殊的例子,checked、selected...等等都有這種現象
在jQuery1.5$("input").attr("checked");為true
在jQuery1.6$("input").attr("checked");為checked
在jQuery1.7$("input").attr("checked");為checked
那如果拿掉checked呢?
則
在jQuery1.5$("input").attr("checked");為false
在jQuery1.6$("input").attr("checked");為undefined
在jQuery1.7$("input").attr("checked");為undefined
另外.attr()也可以針對某元素的屬性設定值給他
方法為.attr( attributeName, value )
二、.prop()
由於.attr()在1.6版以後checked被移除時都會出現undefined,
所以才使用.prop()來解決.attr()問題
經由上面的例子我來跟.prop()比較
在jQuery1.5$("input").attr("checked");為undefined is not a function
在jQuery1.6$("input").attr("checked");為true
在jQuery1.7$("input").attr("checked");為true
那如果拿掉checked呢?
則
在jQuery1.5$("input").attr("checked");為undefined is not a function
在jQuery1.6$("input").attr("checked");為false
在jQuery1.7$("input").attr("checked");為false
小結:
.attr() 與 .prop() 差異的地方還有一點,就是 .attr() 方法可以去添加客制化屬性,
但 .prop() 方法只能添加官方所規範的屬性。
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> </head> <body> <form action="demo_form.asp"> <input type="checkbox" name="vehicle" value="Bike" checked="checked"> I have a bike<br> <input type="checkbox" name="vehicle" value="Car"> I have a car<br> <input type="checkbox" name="vehicle" value="Boat"> I have a boat<br> <input type="submit" value="Submit"> </form> <script> $("input[type='checkbox']").attr({ zoo: "mokey" }); $("input[type='checkbox']").prop({ fruit: "apple" });//無效 $("input[type='checkbox']").prop({ class: "banana" }); </script> </body> </html>
參考資料: